
    bi_                        d Z ddlZddlmZmZmZmZ ddlmZ ddl	m
Z
mZmZ  e
       rddlZddlmZmZmZmZ  ej&                  e      Z	 ddlmZ 	 	 	 	 d&d
eeef   deeed   df      deeedf      ded   ded   f
dZdefdZd Zddde de ddfdZ!de ddddded   fd Z"d! Z#ejH                  d"        Z%d'd#ee   fd$Z&d'd#ee   fd%Z'y# eef$ r d	 ZY w xY w)(z1
PyTorch utilities: Utilities related to PyTorch
    N)ListOptionalTupleUnion   )logging)is_torch_availableis_torch_npu_availableis_torch_version)fftnfftshiftifftn	ifftshift)allow_in_graphc                     | S N )clss    V/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/utils/torch_utils.pymaybe_allow_in_graphr   #   s    
    shape	generatorztorch.Generatordeviceztorch.devicedtypeztorch.dtypelayoutztorch.layoutc           
         t        |t              rt        j                  |      }|}| d   }|xs t        j                  }|xs t        j                  d      }|t        |t
              s|j                  j                  n|d   j                  j                  }||j                  k7  r,|dk(  r'd}|dk7  rFt        j                  d| d| d| d       n&||j                  k7  r|d	k(  rt        d
| d| d      t        |t
              rt        |      dk(  r|d   }t        |t
              rcd| dd z   } t        |      D cg c]  }t        j                  | ||   |||      ! }	}t        j                  |	d      j                  |      }	|	S t        j                  | ||||      j                  |      }	|	S c c}w )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 zl. Note that one can probably slightly 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   )r   r   r   r   dim)
isinstancestrtorchr   stridedlisttypeloggerinfo
ValueErrorlenrangerandncatto)
r   r   r   r   r   rand_device
batch_sizegen_device_typeilatentss
             r   randn_tensorr7   '   s    &#f%KqJ$u}}F*u||E*F7A)T7R)**//XabcXdXkXkXpXpfkk)o.FKXY_X` aKKQ( Sggmfnnvx
 +60I1&9Z[jZkklmnn )T"s9~':aL	)T"uQRy  :&
 KK1kQV_ef
 
 ))G+..v6 N ++eyTYbhillmstN
s   $F=returnc                     t        dd      st        t        d      syt        | t        j                  j
                  j                        S )z:Check whether the module was compiled with torch.compile()<z2.0.0_dynamoF)r   hasattrr&   r$   r;   
eval_frameOptimizedModulemodules    r   is_compiled_modulerA   Y   s5    W%WUI-Ffemm66FFGGr   c                 4    t        |       r| j                  S | S )z8Unwraps a module if it was compiled with torch.compile())rA   	_orig_modr?   s    r   unwrap_modulerD   `   s    1&96EvEr   x_intorch.Tensor	thresholdscalec                 ~   | }|j                   \  }}}}||dz
  z  dk7  s||dz
  z  dk7  r!|j                  t        j                        }n=|j                  t        j
                  k(  r |j                  t        j                        }t        |d      }t        |d      }|j                   \  }}}}t        j                  ||||f|j                        }	|dz  |dz  }}
||	d|
|z
  |
|z   ||z
  ||z   f<   ||	z  }t        |d      }t        |d      j                  }|j                  | j                        S )	zFourier filter as introduced in FreeU (https://huggingface.co/papers/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   r1   r&   float32r   bfloat16r   r   onesr   r   r   real)rE   rG   rH   xBCHWx_freqmaskcrowccol
x_filtereds                r   fourier_filterr[   e   s8    	AJAq!Q 	
QUa1q5ka/DDu}}D%	
ENN	"DDu}}D% !"Ff(+FJAq!Q::q!Ql1884Daa$DZ_DdY	!114)3CdYFV3V	VWd]F v8,Fv8,11J==tzz=**r   resolution_idxhidden_statesres_hidden_states)rF   rF   c                    | dk(  r=|j                   d   dz  }|ddd|f   |d   z  |ddd|f<   t        |d|d         }| dk(  r=|j                   d   dz  }|ddd|f   |d   z  |ddd|f<   t        |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   rL   Nb1s1)rG   rH   b2s2)r   r[   )r\   r]   r^   freeu_kwargsnum_half_channelss        r   apply_freeurf      s     )//2a7/<Q@RAR@R=R/SVbcgVh/ha++++,*+<Q]^bQcd)//2a7/<Q@RAR@R=R/SVbcgVh/ha++++,*+<Q]^bQcd+++r   c                      t         j                  j                         rLt        j                  d      } t         j                  j	                  |       }|d    d|d    }t        |      S y )Nr    r   r!   r   )r&   r    is_availabler   get_device_capabilityfloat)r   compute_capabilitys     r    get_torch_cuda_device_capabilityrl      sb    zz f%"ZZ==fE 21 56a8J18M7NO'((r   c                     t         j                  j                         ryt               ryt	        t         d      rt         j
                  j                         ryt         j                  j                  j                         ryy)Nr    npuxpur   r   )r&   r    rh   r
   r<   ro   backendsr   r   r   r   
get_devicerq      sV    zz 		!		599#9#9#;				(	(	*r   device_typec                     | 
t               } | dv ry t        t        | t        j                        }|j	                          y )N)r   )rq   getattrr&   r    empty_cacherr   
device_mods     r   empty_device_cacherx      s8     lgUZZ8Jr   c                 z    | 
t               } t        t        | t        j                        }|j	                          y r   )rq   rt   r&   r    synchronizerv   s     r   device_synchronizer{      s-     lUZZ8Jr   )NNNNr   )(__doc__	functoolstypingr   r   r   r    r   import_utilsr	   r
   r   r&   	torch.fftr   r   r   r   
get_logger__name__r*   torch._dynamor   r   ImportErrorModuleNotFoundErrorr%   r7   boolrA   rD   intr[   rf   rl   	lru_cacherq   rx   r{   r   r   r   <module>r      s    / /  V V ::			H	%D NR37%)'+//d#457HHIJ/ U3./0/ M"	/
 ^$/dH$ HF
+ +C + + +D,,(6,KY,
)*,6 
 
HSM HSM E 	() s   C 
CC