CoolFace
Apppublic

zparadox/stable-video-diffusion

sourceHugging Faceotherupdated 3y agoView on Hugging Face
0likes
util.cpython-310.pyc84 linesDownload Raw Back to __pycache__
1o

2L]e!�@s@ddlZddlZddlZddlmZddlmZddlZddlZddl	Z	ddl3mZmZm
Z
ddlmZd:dd�Zd	d4�Zdd�Zd:d
d�Zdd�Zd;dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Z d<d)d*�Z!d+d,�Z"d=d-d.�Z#d/d0�Z$d1d2�Z%d>d3d4�Z&d5e'fd6d7�Z(d?d8d9�Z)dS)@�N)�partial)�5isfunction)�Image�	ImageDraw�	ImageFont)�	load_fileTcCs|S)zbOverwrite model.train with this function to make sure train/eval mode6    does not change anymore.�)�self�moderr�5/home/ubuntu/stable-vid/generative-models/sgm/util.py�disabled_trainsrcCsXz%|ddkr |ddkr#t|�}t|�tkr|dWS	W|SW|SW|SY|S)Nr�(������))�eval�type�tuple)�s�trrr�get_string_from_tuples7�8�9�rcCs|dkrdS||d@dkS)a�10    chat.openai.com/chat11    Return True if n is a power of 2, otherwise return False.12 13    The function is_power_of_two takes an integer n as input and returns True if n is a power of 2, otherwise it returns False.14    The function works by first checking if n is less than or equal to 0. If n is less than or equal to 0, it can't be a power of 2, so the function returns False.15    If n is greater than 0, the function checks whether n is a power of 2 by using a bitwise AND operation between n and n-1. If n is a power of 2, then it will have only one bit set to 1 in its binary representation. When we subtract 1 from a power of 2, all the bits to the right of that bit become 1, and the bit itself becomes 0. So, when we perform a bitwise AND between n and n-1, we get 0 if n is a power of 2, and a non-zero value otherwise.16    Thus, if the result of the bitwise AND operation is 0, then n is a power of 2 and the function returns True. Otherwise, the function returns False.17 18    rF�r)�nrrr�is_power_of_two$srcs��fdd�}|S)NcsNtjjj�t��t��d���|i|��Wd�S1s wYdS)N)�enabled�dtype�
cache_enabled)�torch�cuda�amp�autocast�get_autocast_gpu_dtype�is_autocast_cache_enabled)�args�kwargs�r�frr�do_autocast5s�$�zautocast.<locals>.do_autocastr)r%rr&rr$rr4srcCs"tt|d�fi|�dt����S)N�target�params)r�get_obj_from_str�get�dict��configrrr�load_partial_from_config@s"r.�19c20	st|�}t�}t|�D]q}tjd|dd�}t�|�}tjd|d�}t	d|dd��t21||t�r9||d�n||�d	���fd22d�tdt����D��}	z|jd|	d
|d�Wn
t
yhtd�Ynwt�|��ddd�dd}|�|�qt�|�}t�|�}|S)N�RGB�white)�colorzdata/DejaVuSans.ttf)�size�(r��23c3s �|]}�||��VqdS�Nr)�.0�start��ncZtext_seqrr�	<genexpr>Rs�24�z!log_txt_as_img.<locals>.<genexpr>)rr�black)�fill�fontz)Cant encode string for logging. Skipping.�rg�_@g�?)�len�list�ranger�newr�Drawr�truetype�int�25isinstance�join�text�UnicodeEncodeError�print�np�array�	transpose�append�stackr�tensor)26�wh�xcr3�bZtxts�bi�txt�drawr?�linesrr:r�log_txt_as_imgDs.27��2829rZcsG���fdd�d��}|S)Ncs&eZdZej�jg��Ri���ZdS)zpartialclass.<locals>.NewClsN)�__name__�30__module__�__qualname__�	functools�
partialmethod�__init__r�r"�clsr#rr�NewClscsrcr)rbr"r#rcrrar�partialclassbsrdcCs*tj�|�\}}|jdkrtj�|�S|S)N�file)�fsspec�core�	url_to_fs�protocol�os�path�abspath)rk�fs�prrr�make_path_absoluteis31rocCs,t|tj�sdSt|j�dko|jddkS�NF�r��rHr�TensorrA�shape��xrrr�ismappsrxcCs:t|tj�sdSt|j�dko|jddkp|jddkSrprsrvrrr�isimagevs*rycCst|tj�sdS|jdkS)NFr@)rHrrt�ndimrvrrr�	isheatmap|s32r{cCs6t|tj�sdS|jdko|jddkp|jddkS)NF�r@rrr)rHrrtrzrurvrrr�isneighbors�s&r}cCs|duSr7rrvrrr�exists�sr~cCs.|��|��kr|�d�}|��|��ks|S)Nr)�dim�	unsqueeze)rw�yrrr�expand_dims_like�s33�r�cCst|�r|St|�r
|�S|Sr7)r~r)�val�drrr�default�sr�cCs|jttdt|j���d�S)z�34    https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/nn.py#L8635    Take the mean over all non-batch dimensions.36    r)r)�meanrBrCrAru)rRrrr�	mean_flat�sr�FcCs<tdd�|��D��}|rt|jj�d|dd�d��|S)Ncss�|]}|��VqdSr7)�numel)r8rnrrrr<�s�zcount_params.<locals>.<genexpr>z has g�����ư>z.2fz37 M params.)�sum�38parametersrL�	__class__r[)�model�verbose�total_paramsrrr�count_params�sr�cCsHd|vr|dkr39dS|dkrdStd��t|d�di|�dt����S)Nr'Z__is_first_stage__Z__is_unconditional__z%Expected key `target` to instantiate.r(r)�KeyErrorr)r*r+r,rrr�instantiate_from_config�s r�cCsH|�dd�\}}|rt��|rt�|�}t�|�ttj|dd�|�S)N�.r)�package)�rsplit�	importlib�invalidate_caches�
import_module�reload�getattr)�stringr��invalidate_cache�modulerbZ40module_imprrrr)�s4142r)cCst�||�dg�g�S)Nr)r�cat�	new_zerosrvrrr�append_zero�sr�cCs:||j}|dkrtd|j�d|�d���|dd|S)zNAppends dimensions to the end of a tensor until it has target_dims dimensions.rz43input has z dims but target_dims is z, which is less).r7)rz�44ValueError)rwZtarget_dimsZdims_to_appendrrr�append_dims�s45�r�c46Cs�td|���|�d�r%tj|dd�}d|vr td|d���|d}n|�d�r/t|�}nt�t|j�}|j|d	d47�\}}t	|�dkrO|rOtd�t|�t	|�dkr_|r_td
�t|�|rk|�48�D]}	d	|	_qe|��|S)NzLoading model from �ckpt�cpu)�map_location�global_stepz
Global Step: �49state_dict�safetensorsF)�strictrz
missing keys:zunexpected keys:)
rL�endswithr�load�load_safetensors�NotImplementedErrorr�r��load_state_dictrAr��
requires_gradr)50r-r�r��freezeZpl_sd�sdr��m�u�paramrrr�load_model_from_config�s,5152535455r��returncCsbtj�t�}tj�|d�tj�|dd�f}|D]}tj�|�}tj�|�r)|Sqtd|����)z�56    Get the `configs` directory.57    For a working copy, this is the one in the root of the repository,58    but for an installed copy, it's in the `sgm` package (see pyproject.toml).59    �configsz..zCould not find SGM configs in )rjrk�dirname�__file__rIrl�isdir�FileNotFoundError)�this_dir�60candidates�	candidaterrr�get_configs_path�s��r�c61	Cs�|�d�}|dur|dkr|d|�}t|�dksJd��|}d}t|�D]'\}}d�|d|d��}z62t|�}	||	}Wq%tyLt||�}Yq%w|rS||fS|S)a&63    Will return the result of a recursive get attribute call.64    E.g.:65        a.b.c66        = getattr(getattr(a, "b"), "c")67        = get_nested_attribute(a, "b.c")68    If any part of the attribute call is an integer x with current obj a, will69    try to call a[x] instead of a.x first.70    r�Nrz)At least one attribute should be selectedr)�splitrA�	enumeraterIrGr�r�)71�objZattribute_path�depthZ72return_key�73attributesZcurrent_attribute�current_key�level�	attribute�id_rrr�get_nested_attribute�s74 75�r�)T)r/)F)FT)TT)NF)*r^r�rjr�inspectrrf�numpyrMr�PILrrr�safetensors.torchrr�rrrrr.rZrdrorxryr{r}r~r�r�r�r�r�r)r�r�r��strr�r�rrrr�<module>sD7677787980 818283 84