a
    
d                     @   s4   d dl Z d dl mZ G dd dZG dd dZdS )    N)nnc                   @   s0   e Zd Zdd Zdd Zedd Zdd Zd	S )
DDPGradientStatsHookc                 C   s:   z| | | j W n ty,   tdY n0 |   d S )Nz=DDPGradientStatsHook does not support non-DDP wrapped modules)register_comm_hook_hook_fnAttributeError
ValueError_clear_state)selfZ
ddp_module r
   P/var/www/html/stable-diffusion-webui/repositories/k-diffusion/k_diffusion/gns.py__init__   s
    zDDPGradientStatsHook.__init__c                 C   s   g | _ g | _d S )N)bucket_sq_norms_small_batchbucket_sq_norms_large_batchr	   r
   r
   r   r      s    z!DDPGradientStatsHook._clear_statec                    sP   |  } j|d  tjj|tjjj	dd
 } fdd}||S )N   T)opasync_opc                    s&   |   d } j|d  |S )Nr   r   )valuer   appendpowsum)futbufr   r
   r   callback   s    z/DDPGradientStatsHook._hook_fn.<locals>.callback)bufferr   r   r   r   torchdistributed
all_reduceReduceOpAVG
get_futurethen)r	   bucketr   r   r   r
   r   r   r      s
    zDDPGradientStatsHook._hook_fnc                 C   sX   t | j}t | j}|   t||g}tjj|tjjj	d |d 
 |d 
 fS )N)r   r      )r   r   r   r   r   stackr   r   r   r   item)r	   sq_norm_small_batchsq_norm_large_batchstatsr
   r
   r   	get_stats   s    

zDDPGradientStatsHook.get_statsN)__name__
__module____qualname__r   r   staticmethodr   r)   r
   r
   r
   r   r      s
   

r   c                   @   sB   e Zd ZdZdddZdd Zdd	 Zd
d Zdd Zdd Z	dS )GradientNoiseScalea  Calculates the gradient noise scale (1 / SNR), or critical batch size,
    from _An Empirical Model of Large-Batch Training_,
    https://arxiv.org/abs/1812.06162).

    Args:
        beta (float): The decay factor for the exponential moving averages used to
            calculate the gradient noise scale.
            Default: 0.9998
        eps (float): Added for numerical stability.
            Default: 1e-8
    <Nё\?:0yE>c                 C   s,   || _ || _d| _d| _d| _td| _d S )Ng        g      ?nan)betaepsema_sq_normema_varbeta_cumprodfloatgradient_noise_scale)r	   r2   r3   r
   r
   r   r   2   s    zGradientNoiseScale.__init__c                 C   s   t | j S )z3Returns the state of the object as a :class:`dict`.)dict__dict__itemsr   r
   r
   r   
state_dict:   s    zGradientNoiseScale.state_dictc                 C   s   | j | dS )zLoads the object's state.
        Args:
            state_dict (dict): object state. Should be an object returned
                from a call to :meth:`state_dict`.
        N)r:   update)r	   r<   r
   r
   r   load_state_dict>   s    z"GradientNoiseScale.load_state_dictc                 C   s   || ||  ||  }|| d| d|   }| j | j d| j  |  | _| j | j d| j  |  | _|  j| j 9  _t| j| jt| j| j | _| jS )a  Updates the state with a new batch's gradient statistics, and returns the
        current gradient noise scale.

        Args:
            sq_norm_small_batch (float): The mean of the squared 2-norms of microbatch or
                per sample gradients.
            sq_norm_large_batch (float): The squared 2-norm of the mean of the microbatch or
                per sample gradients.
            n_small_batch (int): The batch size of the individual microbatch or per sample
                gradients (1 if per sample).
            n_large_batch (int): The total batch size of the mean of the microbatch or
                per sample gradients.
        r#   )r2   r4   r5   r6   maxr3   r8   )r	   r&   r'   Zn_small_batchZn_large_batchZest_sq_normZest_varr
   r
   r   r=   F   s    zGradientNoiseScale.updatec                 C   s   | j S )z)Returns the current gradient noise scale.)r8   r   r
   r
   r   get_gns\   s    zGradientNoiseScale.get_gnsc                 C   s    | j d| j  | jd| j  fS )zdReturns the current (debiased) estimates of the squared mean gradient
        and gradient variance.r#   )r4   r6   r5   r   r
   r
   r   r)   `   s    zGradientNoiseScale.get_statsN)r/   r0   )
r*   r+   r,   __doc__r   r<   r>   r=   r@   r)   r
   r
   r
   r   r.   %   s   
r.   )r   r   r   r.   r
   r
   r
   r   <module>   s    