a
    –¥»a¬  ã                   @   sn   d Z ddlmZ ddlmZ ddlm  mZ ddl	Z
dd„ Zdd„ Zd	d
„ Zddd„Zdd„ Zddd„ZdS )zK
TensorRT related transformation
Note that ONNX-TRT enforce an NCHW input!
é    )Ú
caffe2_pb2)Ú	workspaceNc                 C   s   dd„ | D ƒS )Nc                 S   s   g | ]
}|j ‘qS © )Z	dim_value©Ú.0Úxr   r   úU/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/caffe2/python/trt/transform.pyÚ
<listcomp>   ó    z'_dim_values_to_list.<locals>.<listcomp>r   )Z
dim_valuesr   r   r   Ú_dim_values_to_list   s    r   c                 C   s*   dd„ | D ƒ}dd„ | D ƒ}t t||ƒƒS )Nc                 S   s   g | ]
}|j ‘qS r   )Únamer   r   r   r   r	      r
   z&_get_output_shapes.<locals>.<listcomp>c                 S   s   g | ]}t |jjjjƒ‘qS r   )r   ÚtypeZtensor_typeÚshapeZdimr   r   r   r   r	      r
   )ÚdictÚzip)Zoutput_value_infosÚnamesZshapesr   r   r   Ú_get_output_shapes   s    r   c               
   C   s>   zt  ¡  W n, ty8 }  ztdƒ‚W Y d } ~ n
d } ~ 0 0 d S )Nz/TensorRT related functions require CUDA support)ÚCZget_cuda_versionÚ	Exception)Ú_r   r   r   Ú
check_gpu_   s    r   é@   é    é   Fc                 C   s<   t ƒ  t |  ¡ t| jjƒ||||¡}t ¡ }| 	|¡ |S )z:
    Convert the whole ONNX model to a TensorRT C2 op
    )
r   r   Zonnx_to_trt_opÚSerializeToStringr   ÚgraphÚoutputr   ZOperatorDefÚParseFromString)Z
onnx_modelÚmax_batch_sizeÚmax_workspace_sizeÚ	verbosityÚdebug_builderZtrt_strÚopr   r   r   Úconvert_onnx_model_to_trt_op#   s    

û
r#   c                 C   s‚   t  | ¡ i }| jD ]h}|jD ]*}||vrt  |¡}t|dƒr|j||< q|jD ]*}||vrPt  |¡}t|dƒrP|j||< qPq|S )Nr   )r   Z
RunNetOncer"   r   Z	FetchBlobÚhasattrr   Úinput)Úpred_netÚinputsÚhintsr"   ÚoZblobÚir   r   r   Ú_infer_shapes8   s    







r+   Tc              	   C   s�   t ƒ  i }|rFi }	| ¡ D ] \}
}tjj|Ž  tj¡|	|
< qt| |	ƒ}| ¡ D ]\}
}|||
< qNt 	|  
¡ ||||||¡}t ¡ }| |¡ |S )zS
    Transform the caffe2_net by collapsing TRT-runnable nodes into trt c2 ops
    )r   ÚitemsÚnpÚrandomZrandnZastypeÚfloat32r+   r   Ztransform_trtr   r   ZNetDefr   )r&   Zinput_shapesZpopulate_shapesr   r   r    r!   Zbuild_serializable_opZshape_hintsZ
input_dataÚkÚvZpred_net_strZpred_net_cutr   r   r   Útransform_caffe2_netJ   s(    


ú
r2   )r   r   r   F)Fr   r   r   FT)Ú__doc__Zcaffe2.protor   Zcaffe2.pythonr   Z!caffe2.python._import_c_extensionÚpythonZ_import_c_extensionr   Únumpyr-   r   r   r   r#   r+   r2   r   r   r   r   Ú<module>   s(   
    ü
      ø