o
    piZ                     @   s.  d Z ddlmZmZmZmZ ddlmZ ddlm	Z	m
Z
 e	 r/ddlZddlmZmZmZmZ eeZzddlmZ W n eefyK   d	d
 ZY nw 				d%deeef deeed df  ded ded ded f
ddZdefddZdddededdfddZded dd!dded" fd#d$ZdS )&z1
PyTorch utilities: Utilities related to PyTorch
    )ListOptionalTupleUnion   )logging)is_torch_availableis_torch_versionN)fftnfftshiftifftn	ifftshift)allow_in_graphc                 C   s   | S )N )clsr   r   Y/home/ubuntu/SoloSpeech/.venv/lib/python3.10/site-packages/diffusers/utils/torch_utils.pymaybe_allow_in_graph"   s   r   shape	generatorztorch.Generatordeviceztorch.devicedtypeztorch.dtypelayoutztorch.layoutc              	      s<  |d }p
t j|pt d}durXttsjjnd jj}||jkrD|dkrDd|dkrCtd| d| d| d n||jkrX|d	krXtd
| d| dttrgt	dkrgd ttrddd   fddt
|D }t j|dd|}|S t j d|}|S )zA helper function to create random tensors on the desired `device` with the desired `dtype`. When
    passing a list of generators, you can seed each batch size individually. If CPU generators are passed, the tensor
    is always created on the CPU.
    r   cpuNmpszBThe passed generator was created on 'cpu' even though a tensor on zB was expected. Tensors will be created on 'cpu' and then moved to zk. Note that one can probably slighly speed up this function by passing a generator that was created on the z device.cudazCannot generate a z! tensor from a generator of type .r   )r   c              	      s$   g | ]}t j|  d qS )r   r   r   r   )torchrandn).0ir   r   r   rand_devicer   r   r   
<listcomp>K   s    z randn_tensor.<locals>.<listcomp>dimr   )r   stridedr   
isinstancelisttypeloggerinfo
ValueErrorlenrangecattor   )r   r   r   r   r   
batch_sizegen_device_typelatentsr   r!   r   randn_tensor&   s<   

r4   returnc                 C   s(   t dds
ttdsdS t| tjjjS )z:Check whether the module was compiled with torch.compile()<z2.0.0_dynamoF)r	   hasattrr   r'   r7   
eval_frameOptimizedModule)moduler   r   r   is_compiled_moduleV   s   r<   x_intorch.Tensor	thresholdscalec                 C   s   | }|j \}}}}||d @ dks||d @ dkr |jtjd}t|dd}t|dd}|j \}}}}tj||||f|jd}	|d |d }
}||	d|
| |
| || || f< ||	 }t|dd}t	|ddj
}|j| jdS )	zFourier filter as introduced in FreeU (https://arxiv.org/abs/2309.11497).

    This version of the method comes from here:
    https://github.com/huggingface/diffusers/pull/5164#issuecomment-1732638706
    r   r   )r   )r$   )r      .)r   r0   r   float32r
   r   onesr   r   r   realr   )r=   r?   r@   xBCHWx_freqmaskcrowccol
x_filteredr   r   r   fourier_filter]   s    &rQ   resolution_idxhidden_statesres_hidden_states)r>   r>   c                 K   s   | dkr*|j d d }|ddd|f |d  |ddd|f< t|d|d d}| dkrT|j d d }|ddd|f |d  |ddd|f< t|d|d	 d}||fS )
a]  Applies the FreeU mechanism as introduced in https:
    //arxiv.org/abs/2309.11497. Adapted from the official code repository: https://github.com/ChenyangSi/FreeU.

    Args:
        resolution_idx (`int`): Integer denoting the UNet block where FreeU is being applied.
        hidden_states (`torch.Tensor`): Inputs to the underlying block.
        res_hidden_states (`torch.Tensor`): Features from the skip block corresponding to the underlying block.
        s1 (`float`): Scaling factor for stage 1 to attenuate the contributions of the skip features.
        s2 (`float`): Scaling factor for stage 2 to attenuate the contributions of the skip features.
        b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
        b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
    r   r   rC   Nb1s1)r?   r@   b2s2)r   rQ   )rR   rS   rT   freeu_kwargsnum_half_channelsr   r   r   apply_freeu|   s   ,,r[   )NNNN)__doc__typingr   r   r   r    r   import_utilsr   r	   r   	torch.fftr
   r   r   r   
get_logger__name__r*   torch._dynamor   r   ImportErrorModuleNotFoundErrorr4   boolr<   intrQ   r[   r   r   r   r   <module>   sN   


0