o
    i e@#                     @   s   d Z ddlZddlZddlZddlmZ ddlmZ ddlm	Z	 ddl
mZ dd Zd	d
 Zdd Zd#ddZd#d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S )$z3Exposes the Python wrapper conversion to trt_graph.    N)version)_pywrap_py_utils)rewriter_config_pb2)dtypesc                 C   s~   t jj}|| _|| _d| j_|| _|| _|| _	d| _
d| _|| _|| _|| _|| _t jj| _d| _|| _|| _|| _|| _dS )z>Modifies rewriter_config to disable all non-TRT optimizations.FTN)r   RewriterConfigOFFarithmetic_optimizationauto_mixed_precisionauto_parallelenableconstant_foldingdebug_stripperdependency_optimizationdisable_meta_optimizerdisable_model_pruningfunction_optimizationimplementation_selectorlayout_optimizerloop_optimization
NO_MEM_OPTmemory_optimizationmin_graph_nodespin_to_host_optimization	remappingscoped_allocator_optimizationshape_optimization)rewriter_configoff r   X/var/www/myenv/lib/python3.10/site-packages/tensorflow/python/compiler/tensorrt/utils.py-disable_non_trt_optimizers_in_rewriter_config   s(   
r!   c                 C   s6   t | tsJ t| dksJ dd | D } d| S )N   c                 S   s   g | ]}t |qS r   )str).0xr   r   r    
<listcomp>:   s    z+version_tuple_to_string.<locals>.<listcomp>.)
isinstancetuplelenjoin)	ver_tupler   r   r    version_tuple_to_string6   s   
r-   c                 C   s$   t t| } t t|}| |kS N)r   Versionr-   )trt_ver
target_verr   r   r    "_is_tensorrt_version_greater_equal>   s   r2   c                 C      t  }t|| ||fS r.   )r   get_linked_tensorrt_versionr2   majorminorpatchverr   r   r    (is_linked_tensorrt_version_greater_equalE      r:   c                 C   r3   r.   )r   get_loaded_tensorrt_versionr2   r5   r   r   r    (is_loaded_tensorrt_version_greater_equalJ   r;   r=   c                 C   s   | t jjddddv S )a!  Determines if a TF-TRT experimental feature is enabled.

  This helper function checks if an experimental feature was enabled using
  the environment variable `TF_TRT_EXPERIMENTAL_FEATURES=feature_1,feature_2`.

  Args:
    feature_name: Name of the feature being tested for activation.
  TF_TRT_EXPERIMENTAL_FEATURES )default,)osenvirongetsplit)feature_namer   r   r    !is_experimental_feature_activatedO   s   
rG   c                 C   s"   t | tr
tj|  S dd | D S )zEHelper function to convert a dtype id to a corresponding string name.c                 S   s   g | ]}t j| qS r   )r   _TYPE_TO_STRING)r$   dr   r   r    r&   c   s    z,_convert_dtype_id_to_str.<locals>.<listcomp>)r(   intr   rH   )dtyper   r   r    _convert_dtype_id_to_str^   s   

rL   c                 C   s   dD ]M}z9| j | }|dkr6|jd}|dkrW q|dkr"W  dS |dkr*W  dS |d	kr2W  d
S W  dS t|jW   S  tyO } zW Y d}~qd}~ww dS )z-Returns the compute DType of a GraphDef Node.)precision_modeDstTrK   TrM   zutf-8r?   FP32float32FP16float16INT8int8unknownN)attrsdecoderL   type	Exception)nodetype_keyprecision_valer   r   r    get_node_compute_dtypef   s(   
r`   c                 C   s2   g }| j | jjD ]}|dd |jD  q	|S )z3Returns the input/output shapes of a GraphDef Node.c                 S   s   g | ]}|j qS r   )size)r$   dimr   r   r    r&      s    z&get_node_io_shapes.<locals>.<listcomp>)rW   listshapeappendrb   )r\   key	out_shaperd   r   r   r    get_node_io_shapes   s   rh   c                 C      t | j| jjS )z1Returns the input/output dtypes of a TRTEngineOp.)rL   rW   rc   rZ   r\   rf   r   r   r    get_trtengineop_io_dtypes      rk   c                 C   ri   )z:Returns the number of input/output nodes of a TRTEngineOp.)r*   rW   rc   rZ   rj   r   r   r    get_trtengineop_io_nodes_count   rl   rm   c                 C   sd   t t}| jjD ]$}| d|jjkr-t|j}|jD ]}||j	  d7  < q ||fS q	||fS )z?Counts the number of nodes and OP types of a given TRTEngineOp._native_segment   )
collectionsdefaultdictrJ   libraryfunction	signaturenamer*   node_defop)graphdef	node_nameops_in_enginefunc
node_countr\   r   r   r    get_trtengineop_node_op_count   s   


r}   c                   @   s   e Zd ZdZdd ZdS )
DTypeIndexzBHelper class to create an index of dtypes with incremental values.c                 C   s    || vrt | d | |< | | S )Nro   )r*   )selfrK   r   r   r    get_dtype_index   s   zDTypeIndex.get_dtype_indexN)__name__
__module____qualname____doc__r   r   r   r   r    r~      s    r~   c              
   C   st  t  }t|d}td|d td|d td|d td|d td|d g }| jD ]x}|j}t|}||}|jdd	 }	|	sGd
}	|j	dkr\t
| |\}
}| d|
 d}n|j	 }d| d|	 d}td| d| d| d|d t|jr|jD ]}|d}tdd|d }td| d| d|d qq-|| q-td|d td|d td|d td|d td |d | D ]\}}td!| d"| d#| d$|d qtd|d td%|d | D ]}|D ]}td| d| d&|d qqtd'|d W d(   n	1 sw   Y  td) td*| d+ td, td- td. td/ td0 d(S )1a9  Exports a GraphDef to GraphViz format.

  - Step 1: Drawing Each Node of the compute GraphDef.
  - Step 2: Create nodes for each collected dtype in the graph.
  - Step 3: Creating invisible links to align properly the legend.

  Each node consequently mentions:
  - Op Type
  - Compute Dtype
  - Compute Device
  wzdigraph tftrt_converted_graph {)filez)  graph [fontsize=10 fontname="Verdana"];z?  node [style=filled height=0.55 colorscheme=set312 shape=box];z
  subgraph tensorflow_graph {z    node [width=1.35];/r   zdevice:UnspecifiedTRTEngineOpz []z<b>z</b>  <br/><i>z</i>z    "z
" [label=<z> fillcolor=z];:z^\^r?   r   z  "z" -> "z";z  }z
  subgraph cluster_legend {z!    label="Compute Dtype Legend";z    margin="30";z    node [width=2];z    z [fillcolor=z label=<<b>z</b>>];z'
  edge[style="invisible", dir="none"];"}NzD
===================================================================z"Graph Visualization Exported to: `z`.zBWe recommend using https://edotor.net/ to visualize the .dot file.zBYou can also use `graphviz` utility to convert them to PNG format:z"  - `sudo apt install -y graphviz`z=  - `dot -Tpng <input_filename>.dot -o <output_filename>.png`zD===================================================================
)r~   openprintr\   ru   r`   r   devicerE   rw   r}   r*   inputresubre   itemskeys)rx   dot_output_filenamedtype_indexfnodes_with_no_inputsr\   output_namenode_precision	color_idx
device_keyr|   _
node_labelinput_full_nameparts
input_namerK   ry   r   r   r    draw_graphdef_as_graphviz   sz   





Cr   )r   r   )r   rp   rB   r   	packagingr   tensorflow.compiler.tf2tensorrtr   tensorflow.core.protobufr   tensorflow.python.frameworkr   r!   r-   r2   r:   r=   rG   rL   r`   rh   rk   rm   r}   dictr~   r   r   r   r   r    <module>   s,   

	