U
    *-e5                     @   s  d dl Z d dlZd dlZd dlmZmZmZ d dlmZm	Z	 d dl
mZ d dlmZ d dlmZ dgZzd dlZdZW n ek
r   d	ZY nX d
dddddZddddddddddddddddgZd dd!d"d#Zered	d$G d%d dZnesed	d$G d&d dZdS )'    N)DictAnyTYPE_CHECKING)_get_qualified_name_format_arg)TensorMetadata)compatibility)chainFxGraphDrawerTFz"AliceBlue"ZLemonChiffon1ZYellow2Z	LightGreyZ
PowderBlue)placeholdercall_module	get_paramget_attroutputZ
CadetBlue1ZCoralZDarkOliveGreen1ZDarkSeaGreen1Z
GhostWhiteZKhaki1ZLavenderBlush1ZLightSkyBlueZ
MistyRose1Z
MistyRose2ZPaleTurquoise2Z
PeachPuff1ZSalmonZThistle1ZThistle3ZWheat1record"filled,rounded"#000000shape	fillcolorstyleZ	fontcolor)Zis_backward_compatiblec                   @   s*  e Zd ZdZd(ejjeeeedddZ	d)e
jdd	d
Ze
jdddZe
jdddZeee
jf dddZejjeeef dddZejjejjejjdddZeedddZejjejjeedddZedddZeedd d!Zejed"d#d$Zejjeeeee
jd%d&d'ZdS )*r
   z
        Visualize a torch.fx.Graph with graphviz
        Basic usage:
            g = FxGraphDrawer(symbolic_traced, "resnet18")
            g.get_dot_graph().write_svg("a.svg")
        FT)graph_modulenameignore_getattrignore_parameters_and_buffersskip_node_names_in_argsc                 C   s   || _ || |||||i| _|jjD ]\}|jdkr6q&| ||}t|tj	j
sRq&| || d|j |||| j| d|j < q&d S )Nr   _)_name_to_dot_dot_graphsgraphnodesop_get_leaf_node
isinstancetorchfxGraphModuletarget)selfr   r   r   r   r   nodeZ	leaf_node r+   ]/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/torch/fx/passes/graph_drawer.py__init__>   s.         
FxGraphDrawer.__init__N)returnc                 C   s   |dkr|   S | |S dS )a  
            Visualize a torch.fx.Graph with graphviz
            Example:
                >>> # xdoctest: +REQUIRES(module:pydot)
                >>> # define module
                >>> class MyModule(torch.nn.Module):
                >>>     def __init__(self):
                >>>         super().__init__()
                >>>         self.linear = torch.nn.Linear(4, 5)
                >>>     def forward(self, x):
                >>>         return self.linear(x).clamp(min=0.0, max=1.0)
                >>> module = MyModule()
                >>> # trace the module
                >>> symbolic_traced = torch.fx.symbolic_trace(module)
                >>> # setup output file
                >>> import ubelt as ub
                >>> dpath = ub.Path.appdir('torch/tests/FxGraphDrawer').ensuredir()
                >>> fpath = dpath / 'linear.svg'
                >>> # draw the graph
                >>> g = FxGraphDrawer(symbolic_traced, "linear")
                >>> g.get_dot_graph().write_svg(fpath)
            N)get_main_dot_graphget_submod_dot_graphr)   Zsubmod_namer+   r+   r,   get_dot_graph^   s    zFxGraphDrawer.get_dot_graphc                 C   s   | j | j S Nr   r   r)   r+   r+   r,   r0   z   s    z FxGraphDrawer.get_main_dot_graphc                 C   s   | j | j d|  S )Nr   r5   r2   r+   r+   r,   r1   }   s    z"FxGraphDrawer.get_submod_dot_graphc                 C   s   | j S r4   )r   r6   r+   r+   r,   get_all_dot_graphs   s    z FxGraphDrawer.get_all_dot_graphs)r*   r/   c                 C   sl   ddddd}|j tkr(t|j  |d< n@||j}tt|  d d d}t	|t
t	  |d< |S )	Nr   z#CAFFE3r   r   r   r         )r"   
_COLOR_MAPZ_pretty_print_targetr(   inthashlibmd5encode	hexdigest_HASH_COLOR_MAPlen)r)   r*   templateZtarget_nameZtarget_hashr+   r+   r,   _get_node_style   s    
 zFxGraphDrawer._get_node_style)moduler*   r/   c                 C   sZ   |}t |jtst|jd}|D ]0}t||sJtt|d | d t||}q$|S )N.z does not have attribute !)r$   r(   strAssertionErrorsplithasattrRuntimeErrorgetattr)r)   rD   r*   Zpy_objZatomsZatomr+   r+   r,   r#      s    
zFxGraphDrawer._get_leaf_node)r(   r/   c                 C   sF   t |tjjrt|}nt |tr*|}nt|}|ddddS )N{\{}\})r$   r%   nnModuletypenamerG   r   replace)r)   r(   retr+   r+   r,   	_typename   s    
zFxGraphDrawer._typename)rD   r*   r   r/   c                    s  fdd}dd|j  d|j d }|jdkr| || |d|   d	 7 }d
}t drzd fdd jD }||d 7 }nj|d| |j d 7 }t|j	dkr|||j	7 }t|j
dkr|||j
7 }|dt|j d 7 }|jd}|| |7 }|d S )Nc                    s   t | tr"d\}}dd | D }n*t | trHd\}}dd |  D }ndS  r^dd |D }t|dkrndS |d	| | }|d
dddS )N)z	|args=(\lz,\n)\lc                 S   s   g | ]}t |d dqS )r8   Zmax_list_lenr   .0ar+   r+   r,   
<listcomp>   s     zSFxGraphDrawer._get_node_label.<locals>._get_str_for_args_kwargs.<locals>.<listcomp>)z|kwargs={\lz,\n}\lc                 S   s&   g | ]\}}| d t |dd qS ): r8   rW   rX   )rZ   kvr+   r+   r,   r\      s    c                 S   s   g | ]}d |kr|qS )%r+   rY   r+   r+   r,   r\      s      r   z,\nrM   rN   rO   rP   )r$   tupledictitemsrA   joinrT   )argprefixsuffixZarg_strs_listZarg_strs)r   r+   r,   _get_str_for_args_kwargs   s    

z?FxGraphDrawer._get_node_label.<locals>._get_str_for_args_kwargsrM   zname=%z	|op_code=
r   \nz\n|r`   __constants__c                    s    g | ]}| d t  | qS )r]   )rL   )rZ   c)leaf_moduler+   r,   r\      s     z1FxGraphDrawer._get_node_label.<locals>.<listcomp>z|target=r   z|num_users=tensor_metarO   )r   r"   r#   rV   rJ   re   rl   r(   rA   argskwargsusersmetaget_tensor_meta_to_label)r)   rD   r*   r   ri   labelextraro   r+   )rn   r   r,   _get_node_label   s(    

zFxGraphDrawer._get_node_labelc                 C   s   |d krdS t |tr | |S t |trJd}|D ]}|| |7 }q2|S t |trxd}| D ]}|| |7 }q`|S t |trd}|D ]}|| |7 }q|S tdt	| d S )Nr`   zUnsupported tensor meta type )
r$   r   _stringify_tensor_metalistru   rc   valuesrb   rK   type)r)   tmresultitemr_   r+   r+   r,   ru      s(    




z#FxGraphDrawer._tensor_meta_to_label)r}   r/   c                 C   sz  d}t |dstd| |dt|j d 7 }|dtt|j d 7 }|dt|j d 7 }|dt|j d 7 }|jrv|j	d k	st
d	|j	kst
|j	d	 }|tjtjhkr|d
t|j	d  d 7 }|dt|j	d  d 7 }nt|tjtjtjhkrN|dt|j	d  d 7 }|dt|j	d  d 7 }|dt|j	d  d 7 }ntd| |dt|j	d	  d 7 }|S )Nr`   dtyper}   z|dtype=rk   z|shape=z|requires_grad=z|stride=qschemez	|q_scale=scalez|q_zero_point=Z
zero_pointz|q_per_channel_scale=z|q_per_channel_zero_point=z|q_per_channel_axis=ZaxiszUnsupported qscheme: z	|qscheme=)rJ   printrG   r   rb   r   Zrequires_gradZstrideZis_quantizedZqparamsrH   r%   Zper_tensor_affineZper_tensor_symmetricZper_channel_affineZper_channel_symmetricZ per_channel_affine_float_qparamsrK   )r)   r}   r~   r   r+   r+   r,   ry      s8    


z$FxGraphDrawer._stringify_tensor_meta)tr/   c                 C   s   t |jt t|j d S )Nrk   )rG   r   rz   r   )r)   r   r+   r+   r,   _get_tensor_label  s    zFxGraphDrawer._get_tensor_label)r   r   r   r   r   r/   c           
   	      s   t j|dd |jjD ]|r*jdkr*q}t jjfd||i|} 	|  fdd}jdkr
||sttjjs|  q|jjD ]6|rjdkrqjD ]}	 t j|	j qq S )a  
            Actual interface to visualize a fx.Graph. Note that it takes in the GraphModule instead of the Graph.
            If ignore_parameters_and_buffers is True, the parameters and buffers
            created with the module will not be added as nodes and edges.
            TB)Zrankdirr   rv   c                     s   t   D ]z\} }jd |  }t|tjjrB|d d nd}tj	|fdd| 
| d it} |  t|j qd S )NrE   z|op_code=get_Z	parameterzbuffer\lrv   rM   rO   )r	   Znamed_parametersZnamed_buffersr   r$   r%   rQ   	ParameterpydotNoder   _WEIGHT_TEMPLATEadd_nodeadd_edgeEdge)ZpnameZptensorZpname1label1Z
dot_w_nodeZ	dot_graphrn   r*   r)   r+   r,   get_module_params_or_buffers4  s$     
z;FxGraphDrawer._to_dot.<locals>.get_module_params_or_buffersr   )r   Dotr    r!   r"   rC   r   r   rx   r   r#   r$   r%   r&   r'   rr   r   r   )
r)   r   r   r   r   r   r   Zdot_noder   userr+   r   r,   r     s0    



zFxGraphDrawer._to_dot)FFT)N)__name__
__module____qualname____doc__r%   r&   r'   rG   boolr-   r   r   r3   r0   r1   r   r7   r   rC   rQ   rR   r#   r   rV   rx   ru   r   ry   ZTensorr   r   r+   r+   r+   r,   r
   5   sH        4c                   @   s$   e Zd ZdejjeedddZdS )r
   F)r   r   r   c                 C   s   t dd S )Nz|FXGraphDrawer requires the pydot package to be installed. Please install pydot through your favorite Python package manager.)rK   )r)   r   r   r   r+   r+   r,   r-   Y  s    r.   N)F)	r   r   r   r%   r&   r'   rG   r   r-   r+   r+   r+   r,   r
   W  s   )r<   r%   Ztorch.fxtypingr   r   r   Ztorch.fx.noder   r   Ztorch.fx.passes.shape_propr   Ztorch.fx._compatibilityr   	itertoolsr	   __all__r   Z	HAS_PYDOTImportErrorr:   r@   r   r
   r+   r+   r+   r,   <module>   sb   
	  "