a
    Þñhˆ7  ã                   @   s*  d dl mZ d dlmZ d dlmZ d dlmZmZ d dl	m
Z
 d dlZd dlZd dlZd dlZd dlmZmZmZmZ dZd	Zd0d
d„Zdd„ Zdd„ Zd1dd„Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Z dd„ Z!G d d!„ d!e"ƒZ#d"d#„ Z$d$d%„ Z%d2d&d'„Z&d(d)„ Z'd*d+„ Z(d,d-„ Z)d.d/„ Z*dS )3é    )Ú
caffe2_pb2)Úcontainer_abcs)Ú	viewitems)ÚDecodeErrorÚMessage)Útext_formatN)Úinteger_typesÚbinary_typeÚ	text_typeÚstring_typesZoptimizer_iterationZiteration_mutexc                    sl   ˆ pg ‰ t ˆ tƒsˆ g‰ tdd„ ˆ D ƒƒs8J d ˆ ¡ƒ‚‡ fdd„}|| ƒ} ||ƒ}| |kpjt| ƒt|ƒkS )zM
    Two ops are identical except for each field in the `ignore_fields`.
    c                 s   s   | ]}t |tƒV  qd S ©N)Ú
isinstancer
   )Ú.0Úf© r   úS/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/caffe2/python/utils.pyÚ	<genexpr>    ó    z OpAlmostEqual.<locals>.<genexpr>z*Expect each field is text type, but got {}c                    s,   t  | ¡} ˆ D ]}|  |¡r|  |¡ q| S r   )ÚcopyÚdeepcopyÚHasFieldZ
ClearField)ÚopÚfield©Úignore_fieldsr   r   Úclean_op#   s
    

zOpAlmostEqual.<locals>.clean_op)r   ÚlistÚallÚformatÚstr)Zop_aZop_br   r   r   r   r   ÚOpAlmostEqual   s    
ÿr    c                 C   sP   | j dkr0tj| jtjd� | j | j| j| j¡S tj| jtjd� | j	j
¡S d S )Nr   ©Údtype)ÚnumÚnpÚasarrayÚdataÚfloat32ÚreshapeZchannelsÚheightÚwidthÚshapeZdim)Zblobr   r   r   ÚCaffeBlobToNumpyArray/   s    
ÿÿr,   c                 C   s\  | j tjjkr(tj| jtjd� | j	¡S | j tjj
krPtj| jtjd� | j	¡S | j tjjkrxtj| jtjd� | j	¡S | j tjjkr tj| jtjd� | j	¡S | j tjjkrÈtj| jtjd� | j	¡S | j tjjk� ròtj| jtjd� | j	¡S | j tjjk�rtj| jtjd� | j	¡S | j tjjk�rFtj| jtjd� | j	¡S tdt| j ƒ ƒ‚d S )Nr!   z$Tensor data type not supported yet: )Ú	data_typer   ÚTensorProtoÚFLOATr$   r%   Ú
float_datar'   r(   ÚdimsÚDOUBLEÚdouble_dataÚfloat64ÚINT64Ú
int64_dataÚint64ÚINT32Ú
int32_dataÚintÚINT16Úint16ÚUINT16Úuint16ÚINT8Úint8ÚUINT8Úuint8ÚRuntimeErrorr   ©Útensorr   r   r   ÚCaffe2TensorToNumpyArray:   sf    ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿrF   c                 C   sð  t  ¡ }|j | j¡ |r ||_| jtjkrTt jj	|_
|j t|  ¡  t¡ƒ¡ �n˜| jtjkrŠt jj|_
|j t|  ¡  tj¡ƒ¡ �nb| jtjkrÀt jj|_
|j t|  ¡  tj¡ƒ¡ �n,| jtjksÚ| jtjk�rt jj|_
|j |  ¡  tj¡ ¡ ¡ nê| jtjk�r8t jj|_
|j t|  ¡  tj¡ƒ¡ n´| jtjk�rnt jj|_
|j t|  ¡  tj¡ƒ¡ n~| jtjk�r¤t jj |_
|j t|  ¡  tj¡ƒ¡ nH| jtj!k�rÚt jj"|_
|j t|  ¡  tj!¡ƒ¡ nt#dt$| jƒ ƒ‚|S )Nz#Numpy data type not supported yet: )%r   r.   r1   Úextendr+   Únamer"   r$   r'   r/   r-   r0   r   ÚflattenZastypeÚfloatr4   r2   r3   r7   r5   r6   r:   Úint32r8   r9   Útolistr<   r;   r>   r=   r@   r?   rB   rA   rC   r   )ZarrrH   rE   r   r   r   ÚNumpyArrayToCaffe2TensorY   s@    

 
 




ÿrM   c              	   C   sR  t  ¡ }| |_t|tjƒ}t|tjƒrL|jj	tj
u rL|j | ¡  ¡ ¡ |S t|tjƒrf| ¡  ¡ }nt|tjƒr|t |¡}t	|ƒtu r’||_�n¼t	|ƒtv sªt	|ƒtu r´||_�nšt|tƒrÈ||_�n†t|tƒrâ| d¡|_�nlt|t jƒrþ|j |¡ �nPt|tƒ�r| ¡ |_�n6|�rLtdd„ |D ƒƒ�rL|j dd„ |D ƒ¡ �n|�r~tdd„ |D ƒƒ�r~|j  dd„ |D ƒ¡ nÐ|�r°tdd„ |D ƒƒ�r°|j! dd„ |D ƒ¡ nž|�rØtd	d„ |D ƒƒ�rØ|j" |¡ nv|�r
td
d„ |D ƒƒ�r
|j! dd„ |D ƒ¡ nD|�r8t#d $| |t	|ƒt%dd„ |D ƒƒ¡ƒ‚nt#d $| |t	|ƒ¡ƒ‚|S )z*Makes an argument based on the value type.úutf-8c                 s   s    | ]}t |ƒttjfv V  qd S r   )ÚtyperJ   r$   Úfloat_©r   Úvr   r   r   r   Ÿ   r   zMakeArgument.<locals>.<genexpr>c                 s   s(   | ] }t |ƒtju r| ¡ n|V  qd S r   )rO   r$   rP   ÚitemrQ   r   r   r   r       s   c                 s   s,   | ]$}t |ƒtv p"t |ƒttjfv V  qd S r   )rO   r   Úboolr$   Úint_rQ   r   r   r   r   £   s   c                 s   s(   | ] }t |ƒtju r| ¡ n|V  qd S r   )rO   r$   rU   rS   rQ   r   r   r   r   ¦   s   c                 s   s"   | ]}t |tƒpt |tƒV  qd S r   )r   r	   r
   rQ   r   r   r   r   ©   s   c                 s   s&   | ]}t |tƒr| d ¡n|V  qdS )rN   N)r   r
   ÚencoderQ   r   r   r   r   ¬   s   ÿc                 s   s   | ]}t |tjƒV  qd S r   )r   r   ÚNetDefrQ   r   r   r   r   °   r   c                 s   s   | ]}t |tƒV  qd S r   )r   r   rQ   r   r   r   r   ²   r   c                 s   s   | ]}|  ¡ V  qd S r   )ÚSerializeToStringrQ   r   r   r   r   ³   r   zBUnknown iterable argument type: key={} value={}, value type={}[{}]c                 s   s   | ]}t |ƒV  qd S r   )rO   rQ   r   r   r   r   ¹   r   z5Unknown argument type: key={} value={}, value type={})&r   ZArgumentrH   r   r   ÚIterabler$   Zndarrayr"   rO   r'   ZfloatsrG   rI   rL   ZgenericZasscalarrJ   r   r   rT   Úir	   Úsr
   rV   rW   ÚnZCopyFromr   rX   r   ÚintsÚstringsÚnetsÚ
ValueErrorr   Úset)ÚkeyÚvalueÚargumentÚiterabler   r   r   ÚMakeArgument}   sl    





ÿÿ
ÿ
ÿ
þ
þÿ
ÿÿrf   c              	   C   sD   | ƒ }zt  ||¡ |W S  t jtfy>   | |¡ | Y S 0 dS )a,  Reads a protobuffer with the given proto class.

    Inputs:
      cls: a protobuffer class.
      s: a string of either binary or text protobuffer content.

    Outputs:
      proto: the protobuffer of cls

    Throws:
      google.protobuf.message.DecodeError: if we cannot decode the message.
    N)r   ÚParseÚ
ParseErrorÚUnicodeDecodeErrorZParseFromString)Úclsr[   Úobjr   r   r   ÚTryReadProtoWithClassÅ   s    
rl   c                 C   s.   t |ƒD ] \}}t| ƒ|u r|| ƒ  S qdS )zNGets a specific field from a protocol buffer that matches the given class
    N)r   rO   )rk   Úfunction_maprj   Úfuncr   r   r   ÚGetContentFromProtoÛ   s    ro   c              	   C   sN   t |ƒD ]8\}}zt|| ƒ}||ƒW   S  ty>   Y qY q0 qtdƒ‚d S )Nz$Cannot find a fit protobuffer class.)r   rl   r   )r[   rm   rj   rn   rk   r   r   r   ÚGetContentFromProtoStringã   s    
rp   c                 C   sr   t |ƒ�}t| | ¡ ƒ}W d  ƒ n1 s,0    Y  t |dƒ�}| | ¡ ¡ W d  ƒ n1 sd0    Y  dS )z:Convert a text file of the given protobuf class to binary.NÚw)Úopenrl   ÚreadÚwriterX   )Zproto_classÚfilenameZout_filenamer   ÚprotoZfidr   r   r   ÚConvertProtoToBinaryî   s    
,rw   c               
   C   sˆ   ddl m} m} |  |jdg dg| | jd¡d�¡ |  d¡}|ddd…f |ddd…f t 	|ddd…f ¡t 	|ddd…f ¡dœS )	z|Get GPU memory usage stats from CUDAContext/HIPContext. This requires flag
       --caffe2_gpu_memory_tracking to be enabledr   ©Ú	workspaceÚcoreZGetGPUMemoryUsageZ____mem____©Zdevice_optionNé   )Ztotal_by_gpuZ
max_by_gpuÚtotalZ	max_total)
Úcaffe2.pythonry   rz   ÚRunOperatorOnceÚCreateOperatorÚDeviceOptionZGpuDeviceTypeZ	FetchBlobr$   Úsum)ry   rz   Úbr   r   r   ÚGetGPUMemoryUsageStatsö   s    üÿ
ür„   c              	   C   s<   ddl m}m} | |jdt| ƒt| ƒ| tj¡d�¡ d S )Nr   rx   ZFreer{   )	r~   ry   rz   r   r€   r   r�   r   ÚCPU)Zblobsry   rz   r   r   r   Ú
ResetBlobs  s    
üÿr†   c                   @   s   e Zd ZdZedd„ ƒZdS )Ú	DebugModea=  
    This class allows to drop you into an interactive debugger
    if there is an unhandled exception in your python script

    Example of usage:

    def main():
        # your code here
        pass

    if __name__ == '__main__':
        from caffe2.python.utils import DebugMode
        DebugMode.run(main)
    c                 C   sj   z|ƒ W S  t y   ‚ Y nJ tyd   dd l}tdƒ tt ¡ d ƒ t | ¡  t d¡ ‚ Y n0 d S )Nr   zjEntering interactive debugger. Type "bt" to print the full stacktrace. Type "help" to see command listing.r|   )ÚKeyboardInterruptÚ	ExceptionÚpdbÚprintÚsysÚexc_infoZpost_mortemÚexit)rj   rn   rŠ   r   r   r   Úrun'  s    ÿ
zDebugMode.runN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Úclassmethodr�   r   r   r   r   r‡     s   r‡   c                 C   s   | |krt d || |¡ƒ‚d S )Nz{}. {} != {})r‰   r   )Úarƒ   Úmsgr   r   r   ÚraiseIfNotEqual;  s    r—   c                    s   t  ˆ ¡‡ fdd„ƒ}|S )z¤
    Use this method to decorate your function with DebugMode's functionality

    Example:

    @debug
    def test_foo(self):
        raise Exception("Bar")

    c                     s   ‡ ‡‡fdd„}t  |¡S )Nc                      s   ˆˆ i ˆ¤ŽS r   r   r   )Úargsr   Úkwargsr   r   rn   N  s    z$debug.<locals>.wrapper.<locals>.func)r‡   r�   )r˜   r™   rn   ©r   )r˜   r™   r   ÚwrapperL  s    zdebug.<locals>.wrapper)Ú	functoolsÚwraps)r   r›   r   rš   r   Údebug@  s    rž   c                 C   s¸   |dur|nt }|dur|nt}ddlm} |  |¡sª| |jtjdgd�¡�J | j	g |dg||j
jd�}|  g |g¡}| ||g|g¡ W d  ƒ q´1 sž0    Y  n
|  |¡}|S )zÕ
    Often, a mutex guarded iteration counter is needed. This function creates a
    mutex iter in the net uniquely (if the iter already existing, it does
    nothing)

    This function returns the iter blob
    Nr   )rz   zdevice_type_override:cpu)Z
extra_infor|   )r+   rc   r"   )ÚOPTIMIZER_ITERATION_NAMEÚITERATION_MUTEX_NAMEr~   rz   ZBlobIsDefinedZDeviceScoper�   r   r…   ZConstantFillZDataTyper5   ZCreateMutexZ
AtomicIterZ
GetBlobRef)Zinit_netÚnetÚiterZ
iter_mutexZiter_valrz   Ú	iterationr   r   r   ÚBuildUniqueMutexIterU  s(    
ÿÿû2
r¤   c              
      s„   t | ƒt ksJ ‚i ‰ t| ƒD ]b}|| ¡ krt| |ƒ‰tˆtƒrˆˆ  ¡ vsvJ d | |ˆ‡ ‡fdd„ˆ D ƒd ˆ¡ƒ‚ˆˆ |< qˆ S )Nz<Failed to resolve {} as Enum: duplicate entries {}={}, {}={}c                    s   g | ]}ˆ | ˆkr|‘qS r   r   )r   rb   ©ÚenumrR   r   r   Ú
<listcomp>†  r   z$EnumClassKeyVals.<locals>.<listcomp>r   )rO   ÚdirÚupperÚgetattrr   r   Úvaluesr   )rj   Úkr   r¥   r   ÚEnumClassKeyValsz  s    

þÿ
r­   c                 C   s¤   i }| D ]–}|  d¡sq|jjD ]r}|jdkr0q |j|jkr`|  |j¡r`t||jƒ||j<  qq |j|jkr t||jƒ}t|ƒdkr |||j<  qq d||j< q|S )z‘
    Convert a list of arguments to a name, value dictionary. Assumes that
    each argument has a name. Otherwise, the argument is skipped.
    rH   r   N)	r   Z
DESCRIPTORÚfieldsrH   ÚlabelZLABEL_OPTIONALrª   ZLABEL_REPEATEDÚlen)r˜   ZansÚargÚdÚlist_r   r   r   Ú
ArgsToDict�  s"    


r´   c                 C   s6   | j dksJ ‚|  d| j d fttd| j d ƒƒ ¡S )Nr|   r   ©ÚndimZ	transposeÚtupleÚrangerD   r   r   r   Ú	NHWC2NCHW¦  s    r¹   c                 C   s,   | j dksJ ‚|  dttd| j ƒƒ d ¡S )Né   )r   )r|   rµ   rD   r   r   r   Ú	NCHW2NHWC«  s    r»   )N)N)NNr   )+Zcaffe2.protor   Zcaffe2.python.compatibilityr   Zfuture.utilsr   Zgoogle.protobuf.messager   r   Zgoogle.protobufr   rŒ   r   rœ   Únumpyr$   Úsixr   r	   r
   r   rŸ   r    r    r,   rF   rM   rf   rl   ro   rp   rw   r„   r†   Úobjectr‡   r—   rž   r¤   r­   r´   r¹   r»   r   r   r   r   Ú<module>   sB   

$H$   û
%