
    
3j;5                       S r SSKJr  SSKrSSKrSSKJrJrJr  SSK	J
r
  SSKJrJrJrJr  \" S5      r\" S	5      r\" 5       (       Ga  SSKrSS
KJrJrJrJr  SSSSSS.r\R2                  R4                  \R6                  R4                  S\R8                  R4                  SS.r\R2                  R<                  \R6                  R<                  S S SS.r\R2                  R@                  \R6                  R@                  \R@                  \R8                  R@                  \R@                  S.r!\R2                  RD                  \#" \R6                  SS5      SSSS.r$\R2                  RJ                  \#" \R6                  SS5      SSSS.r&\R2                  RN                  \#" \R6                  SS5      SSSS.r(\R2                  RR                  \#" \R6                  SS5      SSSS.r*\
RV                  " \,5      r- SSK.J/r0  S*S jr3S+S jr4S,S jr5S,S jr6S,S jr7S,S jr8S,S jr9S,S jr:S,S jr;    S-         S.S jjr<S/S jr=S  r>S0S! jr?        S1S" jr@S# rA\R                  S$ 5       rCS2S3S% jjrDS2S3S& jjrES' rFS( rG\R                  " \R                  5      S4S) j5       rI\" 5       (       a  \C" 5       rJgg! \1\24 a    S r0 Nf = f)5z1
PyTorch utilities: Utilities related to PyTorch
    )annotationsN)Callable	ParamSpecTypeVar   )logging)is_torch_availableis_torch_mlu_availableis_torch_npu_availableis_torch_versionTP)fftnfftshiftifftn	ifftshiftTF)cudaxpucpumpsdefaultc                     gNr    r       U/home/wildlama/miniconda3/lib/python3.13/site-packages/diffusers/utils/torch_utils.py<lambda>r   /       qr   c                     gr   r   r   r   r   r   r   0   r   r   reset_peak_memory_statsmax_memory_allocatedsynchronize)allow_in_graphc                    U $ Nr   )clss    r   maybe_allow_in_graphr'   \   s    
r   c                ^    X;  a  US   " U0 UD6$ X   n[        U5      (       d  U$ U" U0 UD6$ )Nr   )callable)devicedispatch_tableargskwargsfns        r   _device_agnostic_dispatchr/   a   sE    #i($9&99		B B<<	tvr   c                $    [        U [        U5      $ r%   )r/   BACKEND_MANUAL_SEED)r*   seeds     r   backend_manual_seedr3   p   s    $V-@$GGr   c                "    [        U [        5      $ r%   )r/   BACKEND_SYNCHRONIZEr*   s    r   backend_synchronizer7   t       $V-@AAr   c                "    [        U [        5      $ r%   )r/   BACKEND_EMPTY_CACHEr6   s    r   backend_empty_cacher;   x   r8   r   c                "    [        U [        5      $ r%   )r/   BACKEND_DEVICE_COUNTr6   s    r   backend_device_countr>   |   s    $V-ABBr   c                "    [        U [        5      $ r%   )r/   BACKEND_RESET_PEAK_MEMORY_STATSr6   s    r   backend_reset_peak_memory_statsrA      s    $V-LMMr   c                "    [        U [        5      $ r%   )r/   "BACKEND_RESET_MAX_MEMORY_ALLOCATEDr6   s    r   "backend_reset_max_memory_allocatedrD      s    $V-OPPr   c                "    [        U [        5      $ r%   )r/   BACKEND_MAX_MEMORY_ALLOCATEDr6   s    r   backend_max_memory_allocatedrG      s    $V-IJJr   c                L    [        5       (       d  gU [        ;  a  Sn [        U    $ )NFr   )r	   BACKEND_SUPPORTS_TRAININGr6   s    r   backend_supports_trainingrJ      s'    ..$V,,r   c                   [        U[        5      (       a  [        R                  " U5      nUnU S   nU=(       d    [        R                  nU=(       d    [        R                  " S5      nUb  [        U[
        5      (       d  UR                  R                  OUS   R                  R                  nXrR                  :w  a.  US:X  a(  SnUS:w  a  [        R                  SU SU SU S35        O'XrR                  :w  a  US	:X  a  [        S
U SU S35      e[        U[
        5      (       a  [        U5      S:X  a  US   n[        U[
        5      (       a`  SU SS -   n [        U5       Vs/ s H  n[        R                  " XU   XSUS9PM     n	n[        R                  " U	SS9R                  U5      n	U	$ [        R                  " XXSUS9R                  U5      n	U	$ s  snf )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   r   Nr   zBThe 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.r   zCannot generate a z! tensor from a generator of type .r   )r   )	generatorr*   dtypelayoutdim)
isinstancestrtorchr*   stridedlisttypeloggerinfo
ValueErrorlenrangerandncatto)
shaperM   r*   rN   rO   rand_device
batch_sizegen_device_typeilatentss
             r   randn_tensorrf      s    &#f%KqJ$u}}F*u||E*F7A)T7R7R)**//XabcXdXkXkXpXpkk)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k_ef& 	 
 ))G+..v6 N ++ebhillmstN
s   )#Gc                    [        SS5      (       d  [        [        S5      (       d  g[        U [        R                  R
                  R                  5      $ )z:Check whether the module was compiled with torch.compile()<z2.0.0_dynamoF)r   hasattrrT   rR   ri   
eval_frameOptimizedModulemodules    r   is_compiled_modulero      s;    W%%WUI-F-Ffemm66FFGGr   c                >    [        U 5      (       a  U R                  $ U $ )z8Unwraps a module if it was compiled with torch.compile())ro   	_orig_modrm   s    r   unwrap_modulerr      s    1&996EvEr   c                8   U nUR                   u  pEpgXwS-
  -  S:w  d  XfS-
  -  S:w  a  UR                  [        R                  S9nO;UR                  [        R                  :w  a  UR                  [        R                  S9n[        USS9n[        USS9nUR                   u  pEpg[        R                  " XEXg4UR                  S9n	US-  US-  pX)SX-
  X-   2X-
  X-   24'   X-  n[        USS9n[        USS9R                  nUR                  U R                  S9$ )	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   )rN   )rP   r6      .)r`   r_   rT   float32rN   r   r   onesr*   r   r   real)x_in	thresholdscalexBCHWx_freqmaskcrowccol
x_filtereds                r   fourier_filterr      s    	AJA! 	
Uaq5ka/DDu}}D% 
EMM	!DDu}}D% !"Ff(+FJA!::qQl1884Daa$Z_d!1143CdFV3V	VW]F v8,Fv8,11J==tzz=**r   c                   U S:X  a:  UR                   S   S-  nUSS2SU24   US   -  USS2SU24'   [        USUS   S9nU S:X  a:  UR                   S   S-  nUSS2SU24   US   -  USS2SU24'   [        USUS	   S9nX4$ )
a5  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   rv   Nb1s1)r{   r|   b2s2)r`   r   )resolution_idxhidden_statesres_hidden_statesfreeu_kwargsnum_half_channelss        r   apply_freeur      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                     [         R                  R                  5       (       aM  [         R                  " S5      n [         R                  R	                  U 5      nUS    SUS    3n[        U5      $ g )Nr   r   rL   r   )rT   r   is_availabler*   get_device_capabilityfloat)r*   compute_capabilitys     r    get_torch_cuda_device_capabilityr     se    zz  f%"ZZ==fE 21 56a8J18M7NO'((r   c                 Z   [         R                  R                  5       (       a  g[        5       (       a  g[	        [         S5      (       a$  [         R
                  R                  5       (       a  g[         R                  R                  R                  5       (       a  g[        5       (       a  gg)Nr   npur   r   mlur   )	rT   r   r   r   rj   r   backendsr   r
   r   r   r   
get_devicer     sq    zz  		!	!			599#9#9#;#;				(	(	*	*		!	!r   c                    U c
  [        5       n U S;   a  g [        [        U [        R                  5      nUR	                  5         g )N)r   )r   getattrrT   r   empty_cachedevice_type
device_mods     r   empty_device_cacher   /  s8     lgUZZ8Jr   c                |    U c
  [        5       n [        [        U [        R                  5      nUR	                  5         g r%   )r   r   rT   r   r"   r   s     r   device_synchronizer   8  s-     lUZZ8Jr   c                 J   S[         R                  S'   S[         R                  S'   [        R                  " S5        S[        R                  R
                  l        S[        R                  R
                  l        S[        R                  R                  R                  l
        g)z
Helper function for reproducible behavior during distributed training. See
- https://pytorch.org/docs/stable/notes/randomness.html for pytorch
1CUDA_LAUNCH_BLOCKINGz:16:8CUBLAS_WORKSPACE_CONFIGTFN)osenvironrT   use_deterministic_algorithmsr   cudnndeterministic	benchmarkr   matmul
allow_tf32r   r   r   enable_full_determinismr   ?  sn     *-BJJ%&,3BJJ()	&&t, *.ENN&%*ENN",1ENN)r   c                 |    S[         R                  S'   S[         R                  S'   [        R                  " S5        g )N0r    r   F)r   r   rT   r   r   r   r   disable_full_determinismr   Q  s.    ),BJJ%&,.BJJ()	&&u-r   c                   ^ ^ SU U4S jjnU$ )Nc                   >^ ^ [         R                  " TTS9" T 5      m[        SS5      (       a  T$ [         R                  " T 5      SUU 4S jj5       nU$ )N)maxsizetypedrh   z2.7.0c                   > [        [        SS 5      n[        U=(       a#    [        US5      =(       a    UR	                  5       5      n[        U=(       a#    [        US5      =(       a    UR                  5       5      nU(       d5  [        [        SS 5      nUb!  [        US5      (       a  UR                  5       nU(       d  U(       a  T" U 0 UD6$ T" U 0 UD6$ )Ncompileris_exportingis_compilingri   )r   rT   boolrj   r   r   )r,   r-   r   r   r   dynamocachedr.   s         r   inner_wrapperElru_cache_unless_export.<locals>.outer_wrapper.<locals>.inner_wrapper^  s    uj$7H jWX~-N jS[ShShSjkL jWX~-N jS[ShShSjkL   	48%'&.*I*I#)#6#6#8L|4*6**4*6**r   )r,   zP.argsr-   zP.kwargs)	functools	lru_cacher   wraps)r.   r   r   r   r   s   ` @r   outer_wrapper.lru_cache_unless_export.<locals>.outer_wrapperY  sO    $$WEB2FC))M			+ 
	+ r   )r.   zCallable[P, T]r   )r   r   r   s   `` r   lru_cache_unless_exportr   W  s     . r   )r*   rS   r+   zdict[str, callable])r*   rS   r2   int)r*   rS   )NNNN)
r`   ztuple | listrM   z2list['torch.Generator'] | 'torch.Generator' | Noner*   zstr | 'torch.device' | NonerN   z'torch.dtype' | NonerO   z'torch.layout' | None)returnr   )rz   'torch.Tensor'r{   r   r|   r   r   r   )r   r   r   r   r   r   r   z%tuple['torch.Tensor', 'torch.Tensor']r%   )r   z
str | None)   F)K__doc__
__future__r   r   r   typingr   r   r   r   r   import_utilsr	   r
   r   r   r   r   rT   	torch.fftr   r   r   r   rI   r   r   r   r   r:   device_countr=   manual_seedr1   r    r   r@   reset_max_memory_allocatedrC   r!   rF   r"   r5   
get_logger__name__rX   torch._dynamor#   r'   ImportErrorModuleNotFoundErrorr/   r3   r7   r;   r>   rA   rD   rG   rJ   rf   ro   rr   r   r   r   r   r   r   r   r   r   r   r   torch_devicer   r   r   <module>r      s   #  	 / /  n n CLcN ::)-d4PUbf g

&&yy$$yy$$ 

''yy%% 

&&yy$$  yy$$$$ 

22uyy";TB'# 

55uyy";TB*& 

//uyy"8$?$  

&&uyy-6 
		H	%DHBBCNQK- EI*."&$(//A/ (/  	/
 "/dHF
!+H,,(6,KY,*,6  2$. $$% &6 <L s 	() s   ;J> >KK