
    i/                        d Z ddlZddlZddlmZmZmZmZmZm	Z	 ddl
mZ ddlmZmZmZmZ  e       rddlZddlmZmZmZmZ dddd	dd
Zej0                  j2                  ej4                  j2                  dej6                  j2                  dd
Zej0                  j:                  ej4                  j:                  d d dd
Zej0                  j>                  ej4                  j>                  ej>                  ej6                  j>                  ej>                  d
Z ej0                  jB                   e"ej4                  dd      dddd
Z#ej0                  jH                   e"ej4                  dd      dddd
Z%ej0                  jL                   e"ej4                  dd      dddd
Z'ej0                  jP                   e"ej4                  dd      dddd
Z) ejT                  e+      Z,	 ddl-m.Z/ de2dee2ef   fdZ3de2de4fdZ5de2fdZ6de2fdZ7de2fdZ8de2fdZ9de2fdZ:de2fdZ;de2fdZ<	 	 	 	 d;de	eef   dee	ed    d f      dee	e2d!f      d"ed#   d$ed%   f
d&Z=d'e>fd(Z?d) Z@d*d+d,e4d-e4d'd+fd.ZAd/e4d0d+d1d+d'ed2   fd3ZBd4 ZCej                  d5        ZEd<d6ee2   fd7ZFd<d6ee2   fd8ZGd9 ZHd: ZI e       r eE       ZJyy# e0e1f$ r d Z/Y w xY w)=z1
PyTorch utilities: Utilities related to PyTorch
    N)CallableDictListOptionalTupleUnion   )logging)is_torch_availableis_torch_mlu_availableis_torch_npu_availableis_torch_version)fftnfftshiftifftn	ifftshiftTF)cudaxpucpumpsdefaultc                       yNr    r       e/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/diffusers/utils/torch_utils.py<lambda>r   )       r   c                       yr   r   r   r   r   r   r   *   r   r   reset_peak_memory_statsmax_memory_allocatedsynchronize)allow_in_graphc                     | S Nr   )clss    r   maybe_allow_in_graphr'   V   s    
r   devicedispatch_tablec                 T    | |vr |d   |i |S ||    }t        |      s|S  ||i |S )Nr   )callable)r(   r)   argskwargsfns        r   _device_agnostic_dispatchr/   [   sI    ^#(~i($9&99		B B<	tvr   seedc                 $    t        | t        |      S r%   )r/   BACKEND_MANUAL_SEED)r(   r0   s     r   backend_manual_seedr3   j   s    $V-@$GGr   c                 "    t        | t              S r%   )r/   BACKEND_SYNCHRONIZEr(   s    r   backend_synchronizer7   n       $V-@AAr   c                 "    t        | t              S r%   )r/   BACKEND_EMPTY_CACHEr6   s    r   backend_empty_cacher;   r   r8   r   c                 "    t        | t              S r%   )r/   BACKEND_DEVICE_COUNTr6   s    r   backend_device_countr>   v   s    $V-ABBr   c                 "    t        | t              S r%   )r/   BACKEND_RESET_PEAK_MEMORY_STATSr6   s    r   backend_reset_peak_memory_statsrA   z   s    $V-LMMr   c                 "    t        | t              S r%   )r/   "BACKEND_RESET_MAX_MEMORY_ALLOCATEDr6   s    r   "backend_reset_max_memory_allocatedrD   ~   s    $V-OPPr   c                 "    t        | t              S r%   )r/   BACKEND_MAX_MEMORY_ALLOCATEDr6   s    r   backend_max_memory_allocatedrG      s    $V-IJJr   c                 >    t               sy| t        vrd} t        |    S )NFr   )r   BACKEND_SUPPORTS_TRAININGr6   s    r   backend_supports_trainingrJ      s$    ..$V,,r   shape	generatorztorch.Generatorz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   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	   )rL   r(   rM   rN   dim)
isinstancestrtorchr(   stridedlisttypeloggerinfo
ValueErrorlenrangerandncatto)
rK   rL   r(   rM   rN   rand_device
batch_sizegen_device_typeilatentss
             r   randn_tensorrf      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   hasattrrU   rS   rj   
eval_frameOptimizedModulemodules    r   is_compiled_modulerp      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())rp   	_orig_modrn   s    r   unwrap_modulers      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   )rM   )rQ   r6      .)rK   r`   rU   float32rM   bfloat16r   r   onesr(   r   r   real)rt   rv   rw   xBCHWx_freqmaskcrowccol
x_filtereds                r   fourier_filterr      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)ru   ru   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 )
ad  Applies the FreeU mechanism as introduced in https://huggingface.co/papers/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	   r{   Nb1s1)rv   rw   b2s2)rK   r   )r   r   r   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                      t         j                  j                         rLt        j                  d      } t         j                  j	                  |       }|d    d|d    }t        |      S y )Nr   r   rP   r	   )rU   r   is_availabler(   get_device_capabilityfloat)r(   compute_capabilitys     r    get_torch_cuda_device_capabilityr     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t               ryy)Nr   npur   r   mlur   )	rU   r   r   r   rk   r   backendsr   r   r   r   r   
get_devicer     s_    zz 		!		599#9#9#;				(	(	*		!r   device_typec                     | 
t               } | dv ry t        t        | t        j                        }|j	                          y )N)r   )r   getattrrU   r   empty_cacher   
device_mods     r   empty_device_cacher   '  s8     lgUZZ8Jr   c                 z    | 
t               } t        t        | t        j                        }|j	                          y r%   )r   r   rU   r   r"   r   s     r   device_synchronizer   0  s-     lUZZ8Jr   c                  H   dt         j                  d<   dt         j                  d<   t        j                  d       dt        j                  j
                  _        dt        j                  j
                  _        dt        j                  j                  j                  _
        y)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environrU   use_deterministic_algorithmsr   cudnndeterministic	benchmarkr   matmul
allow_tf32r   r   r   enable_full_determinismr   7  sn     *-BJJ%&,3BJJ()	&&t, *.ENN&%*ENN",1ENN)r   c                  z    dt         j                  d<   dt         j                  d<   t        j                  d       y )N0r    r   F)r   r   rU   r   r   r   r   disable_full_determinismr   I  s.    ),BJJ%&,.BJJ()	&&u-r   )NNNNr%   )K__doc__	functoolsr   typingr   r   r   r   r   r   r   r
   import_utilsr   r   r   r   rU   	torch.fftr   r   r   r   rI   r   r   r   r   r:   device_countr=   manual_seedr2   r    r   r@   reset_max_memory_allocatedrC   r!   rF   r"   r5   
get_logger__name__rY   torch._dynamor#   r'   ImportErrorModuleNotFoundErrorrT   r/   intr3   r7   r;   r>   rA   rD   rG   rJ   rf   boolrp   rs   r   r   r   	lru_cacher   r   r   r   r   torch_devicer   r   r   <module>r      s    	 ? ?  n n ::)-d4PUbf g

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

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

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

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

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

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

&&uyy-6 
		H	%Dc 4X;N H H3 HB BB BC CNC NQs QK K-c - NR37%)'+//d#457HHIJ/ U3./0/ M"	/
 ^$/dH$ HF
+ +C + + +D,,(6,KY,
)*,6  HSM HSM 2$. <L w 	() s   &J? ?
KK