a
    dC                     @   sT   d Z ddlmZmZ ddlZddlmZ d	eeeee	f e	ee	ef dddZ
dS )
z Utilities to describe gradients.    )DictUnionN)Module/)module	norm_typegroup_separatorreturnc                    sx   t dkrtd  fdd|  D }|rbtt| }||d d< dd | D }|S )a  Compute each parameter's gradient's norm and their overall norm.

    The overall norm is computed over all gradients together, as if they
    were concatenated into a single vector.

    Args:
        module: :class:`torch.nn.Module` to inspect.
        norm_type: The type of the used p-norm, cast to float if necessary.
            Can be ``'inf'`` for infinity norm.
        group_separator: The separator string used by the logger to group
            the gradients norms in their own subfolder instead of the logs one.

    Return:
        norms: The dictionary of p-norms of each parameter's gradient and
            a special entry for the total p-norm of the gradients viewed
            as a single vector.
    r   zD`norm_type` must be a positive number or 'inf' (infinity norm). Got c                    s:   i | ]2\}}|j d urd d  | |j jqS )Ngrad_Z_norm)Zgraddatanorm).0namepr   r    j/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/pytorch_lightning/utilities/grads.py
<dictcomp>+   s   
zgrad_norm.<locals>.<dictcomp>r
   Z_norm_totalc                 S   s    i | ]\}}|t | d qS )   )rounditem)r   kvr   r   r   r   3       )	float
ValueErrorZnamed_parameterstorchZtensorlistvaluesr   items)r   r   r   ZnormsZ
total_normr   r   r   	grad_norm   s    r    )r   )__doc__typingr   r   r   Ztorch.nnr   r   intstrr    r   r   r   r   <module>   s   