a
    –¥»aF@  ã                   @   sš  d dl mZ d dlmZmZ d dlmZ d dlmZm	Z	m
Z
mZmZmZmZmZ d dlZd dlmZ d dlm  mZ d dlmZ d dlZd dlmZ d dlm  mZ d dlZd dl Z d dl!Z!d dl"m#Z# e$ee$e$f dœd	d
„Z%ee ej&e	e$e
f dœdd„Z'ej&e	e$e
f ejj(dœdd„Z)d0ejj(ejj(dœdd„Z*ej(ej(dœdd„Z+ej(eej& eej& eej& dœdd„Z,ej-ej.ej/ej0ej1ej2ej3ej4ej5ej6ej4ej7ej8gZ9ej:ej;gZ<ej-ej=ej.ej>ej/dd„ iZ?eej& e	e$ej(f dœdd„Z@eej& e	e$ej(f e	ej(ej(f dœd d!„ZAG d"d#„ d#ƒZBd1d&d'„ZCeBeDd(œd)d*„ZEG d+d,„ d,ƒZFdejGfejj(ee	e$e
f  eejG ejj(d-œd.d/„ZHdS )2é    N)ÚArgumentÚTarget)Úfuse_conv_bn_eval)ÚTypeÚDictÚAnyÚTupleÚIterableÚOptionalÚListÚcast)Ú	ShapeProp)Údefaultdict)ÚEnum)ÚtargetÚreturnc                 C   s&   |   dd¡�^ }}|r|d nd|fS )zp
    Splits a qualname into parent path and last atom.
    For example, `foo.bar.baz` -> (`foo.bar`, `baz`)
    Ú.é   r   Ú )Úrsplit)r   ÚparentÚname© r   ú\/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/torch/fx/experimental/optimization.pyÚ_parent_name   s    r   )ÚpatternÚnodeÚmodulesc                 C   s”   t |jƒdkrdS |jd |f}t| |ƒD ]d\}}t|tjƒsD dS |jdkrT dS t|jtƒsf dS |j|vrv dS t	||j ƒ|ur* dS q*dS )Nr   FÚcall_moduleT)
ÚlenÚargsÚzipÚ
isinstanceÚfxÚNodeÚopr   ÚstrÚtype)r   r   r   ÚnodesÚexpected_typeZcurrent_noder   r   r   Úmatches_module_pattern   s    

r*   )r   r   Ú
new_modulec                 C   s<   t | jtƒsJ ‚t| jƒ\}}||| j< t|| ||ƒ d S ©N)r"   r   r&   r   Úsetattr)r   r   r+   Úparent_namer   r   r   r   Úreplace_node_module,   s    
r/   F)Úmodelr   c                 C   sæ   t jt jft jt jft jt jfg}|s0t | ¡} t	 
| ¡}t| ¡ ƒ}t |j¡}|D ]‚}|jD ]v}t|||ƒr`t|jd jƒdkr†q`||jd j }||j }	t||	ƒ}
t|jd ||
ƒ | |jd ¡ | |¡ q`qVt	 ||¡S )z�
    Fuses convolution/BN layers for inference purposes. Will deepcopy your
    model by default, but can modify the model inplace as well.
    r   r   )ÚnnZConv1dZBatchNorm1dÚConv2dÚBatchNorm2dZConv3dZBatchNorm3dÚcopyÚdeepcopyr#   Úsymbolic_traceÚdictÚnamed_modulesÚgraphr(   r*   r   r    Úusersr   r   r/   Úreplace_all_uses_withÚ
erase_nodeÚGraphModule)r0   ZinplaceÚpatternsÚfx_modelr   Ú	new_graphr   r   ÚconvZbnZ
fused_convr   r   r   Úfuse2   s*    


þ




rB   c                 C   s*   t  | ¡}G dd„ dtj jƒ}||ƒ ¡ S )z5
    Removes all dropout layers from the module.
    c                       s8   e Zd Zeeedf eeef edœ‡ fdd„Z	‡  Z
S )z&remove_dropout.<locals>.DropoutRemover.)r   r    Úkwargsr   c                    s>   t | j| tjƒr*t|ƒdks"J ‚|d S tƒ  |||¡S d S )Nr   r   )r"   Z
submodulesr1   ZDropoutr   Úsuperr   )Úselfr   r    rC   ©Ú	__class__r   r   r   T   s    z2remove_dropout.<locals>.DropoutRemover.call_module)Ú__name__Ú
__module__Ú__qualname__r   r   r   r   r&   r   r   Ú__classcell__r   r   rF   r   ÚDropoutRemoverS   s   rL   )r#   r6   ÚtorchZTransformerZ	transform)r0   r?   rL   r   r   r   Úremove_dropoutM   s    
rN   )Úorig_moduler(   ÚinputsÚoutputsc                    s|   t  ¡ }i ‰ |D ]}| |j¡}|ˆ |< q|D ] }| |‡ fdd„¡}|ˆ |< q.| ‡ fdd„|D ƒ¡ | ¡  t  | |¡S )z�
    Given lists of nodes from an existing graph that represent a subgraph, returns a submodule that executes that subgraph.
    c                    s   ˆ |  S r,   r   )Úx©Úenvr   r   Ú<lambda>f   ó    z"extract_subgraph.<locals>.<lambda>c                    s   g | ]}ˆ | ‘qS r   r   )Ú.0ÚoutputrS   r   r   Ú
<listcomp>h   rV   z$extract_subgraph.<locals>.<listcomp>)r#   ÚGraphÚplaceholderr   Z	node_copyrX   Úlintr=   )rO   r(   rP   rQ   r@   ÚinputÚnew_noder   r   rS   r   Úextract_subgraph\   s    

r_   c                 C   s
   t  | ¡S r,   )Ú	th_mkldnnZMkldnnBatchNorm)ÚaÚ_r   r   r   rU   y   rV   rU   )r(   r   c                 C   s€   i }| D ]r}|j dkrt|jtƒs&J ‚||j }t|ƒtv rtt|ƒ |tjƒ}t|tj	ƒs`J ‚t
 |¡||< t|||ƒ q|S )zÈ
    For each node, if it's a module that can be preconverted into MKLDNN,
    then we do so and create a mapping to allow us to convert from the MKLDNN
    version of the module to the original.
    r   )r%   r"   r   r&   r'   Ú
mkldnn_maprM   Úfloatr1   ÚModuler4   r5   r/   )r(   r   Úold_modulesr   Ú
cur_moduler+   r   r   r   Úmodules_to_mkldnn}   s    

rh   )r(   r   rf   c                 C   sJ   | D ]@}|j dkrt|jtƒs"J ‚||j }||v rt|||| ƒ qdS )za
    Maps each module that's been changed with `modules_to_mkldnn` back to its
    original.
    r   N)r%   r"   r   r&   r/   )r(   r   rf   r   rg   r   r   r   Úreset_modules�   s    

ri   c                   @   s   e Zd Zejdœdd„ZdS )ÚMklSubgraph©Úfx_graphc                 C   s   || _ g | _g | _g | _d S r,   )rl   r(   Ústart_nodesÚ	end_nodes)rE   rl   r   r   r   Ú__init__œ   s    zMklSubgraph.__init__N)rH   rI   rJ   r#   rZ   ro   r   r   r   r   rj   ›   s   rj   é
   r   c                    s(   d‰d‰t tdœ‡ ‡‡‡‡fdd„}|S )aW  
    This generates a heuristic that can be passed into `optimize_for_inference` that
    determines whether a subgraph should be run in MKL by running it with the example_inputs.

    Example usage:
        heuristic = gen_mkl_autotuner(example_inputs, iters=10)
        fast_model = optimization.optimize_for_inference(model, heuristic)
    N©r9   r   c                    s¸   | j }ˆd u r,| jj‰| jj‰tˆƒ ˆ¡ dd„ |D ƒ‰ tttj	 dd„ | j
D ƒƒ}tˆ| j||ƒ‰‡‡fdd„}|‡ ‡fdd„ƒ}tˆjjtˆ ¡ ƒˆƒ |‡ ‡fdd„ƒ}||k S )	Nc                 S   s   g | ]}t  |j¡‘qS r   )rM   ZrandnÚshape©rW   r   r   r   r   rY   µ   rV   z@gen_mkl_autotuner.<locals>.use_mkl_heuristic.<locals>.<listcomp>c                 S   s   g | ]}|j d  ‘qS )r   )r    rs   r   r   r   rY   ¶   rV   c                    s<   t ˆƒD ]
}| ƒ  qt ¡ }t ˆ ƒD ]
}| ƒ }q$t ¡ | S r,   )ÚrangeÚtime)Úfrb   ÚbeginÚout)ÚitersÚwarmupr   r   Ú	benchmark¹   s    z?gen_mkl_autotuner.<locals>.use_mkl_heuristic.<locals>.benchmarkc                      s   dd„ ˆdd„ ˆ D ƒŽ D ƒS )Nc                 S   s   g | ]}|  ¡ ‘qS r   ©Úto_dense©rW   Úir   r   r   rY   Á   rV   zRgen_mkl_autotuner.<locals>.use_mkl_heuristic.<locals>.<lambda>.<locals>.<listcomp>c                 S   s   g | ]}|  ¡ ‘qS r   )Ú	to_mkldnnr~   r   r   r   rY   Á   rV   r   r   ©Zsample_inputsÚ	submoduler   r   rU   Á   rV   z>gen_mkl_autotuner.<locals>.use_mkl_heuristic.<locals>.<lambda>c                      s   ˆˆ Ž S r,   r   r   r�   r   r   rU   Ä   rV   )rm   rl   Zowning_modulerf   r   Ú	propagater   r   r#   r$   rn   r_   r(   ri   r9   r7   r8   )r9   Zinput_nodesZoutput_argsr{   Zmkl_timeZno_mkl_time©Úexample_inputsr?   ry   rf   rz   r�   r   Úuse_mkl_heuristic®   s    z,gen_mkl_autotuner.<locals>.use_mkl_heuristic)rj   Úbool)r…   ry   rz   r†   r   r„   r   Úgen_mkl_autotuner¢   s    	rˆ   rq   c                 C   s   t | jƒdkS )z¿
    This is a heuristic that can be passed into `optimize_for_inference` that
    determines whether a subgraph should be run in MKL by checking if there
    are more than 2 nodes in it
    é   )r   r(   )r9   r   r   r   Úuse_mkl_lengthÈ   s    rŠ   c                   @   sB   e Zd Zdd„ Zedœdd„Zeedœdd„Zeed	œd
d„ZdS )Ú	UnionFindc                 C   s   d g| | _ dg| | _d S )Nr   ©r   Úsize)rE   Únr   r   r   ro   Ñ   s    zUnionFind.__init__)Úvc                 C   s   || j |< d| j|< d S )Nr   rŒ   )rE   r�   r   r   r   Úmake_setÕ   s    
zUnionFind.make_set)r�   r   c                 C   sB   | j | }||kr|S |d us"J ‚|  |¡| j |< tt| j | ƒS r,   )r   Úfindr   Úint)rE   r�   Úparr   r   r   r‘   Ù   s    
zUnionFind.find)ra   Úbc                 C   sf   |   |¡|   |¡ }}||kr"|S | j| | j| k r@|| }}|| j|< | j|  | j| 7  < d S r,   )r‘   r�   r   )rE   ra   r”   r   r   r   Újoiná   s    

zUnionFind.joinN)rH   rI   rJ   ro   r’   r�   r‘   r•   r   r   r   r   r‹   Ð   s   r‹   )r0   Úpass_configÚtracerr   c              	      sP  dddt idœ}|du ri }| |¡ |d r6t| ƒ} |d rFt| ƒ} |d du rV| S t|d tƒsltd	ƒ‚d|d vr€td
ƒ‚|d d }|ƒ }| t 	| ¡¡‰ t
 |jˆ ¡}t|  ¡ ƒ}G dd„ dtƒ}tˆ jƒD �]‚}	|j}
|	jdk�rV||	j }t|ƒtv �rˆ|j}
t| ¡ dƒ}|du�rˆ|jtjk�s:J dƒ‚|jt d¡k�sˆJ dƒ‚n2|	jdk�rˆ|	jtv �rv|j}
n|	jtv �rˆ|j}
|
|jkrÖ|
|jk�r¶tdd„ |	j D ƒƒ�s¶qÖˆ  !|	¡�& t
 "|	j ‡ fdd„¡}W d  ƒ n1 �sî0    Y  t#t$t
j%j& |ƒ|	_ ˆ  '|	¡�2 ˆ  (dd|	f¡}|	 )|¡ |	f|_ W d  ƒ qÖ1 �sP0    Y  qÖt*tˆ jƒ|ƒ}|ˆ _+ˆ jD ]„}	|	jdk�rx|	jdk�rx|	j d }t|	j,ƒ}|D ]2}|jdk�r¬|jdk�r¬| )|¡ ˆ  -|¡ �q¬t.|	j,ƒdk�rxˆ  -|	¡ �qxt.ˆ jƒ}t/|ƒ‰‡fdd„‰t0ˆ jƒD ]ê\}}	|	jdk�rX|	jdk�rX||	_1ˆ 2|¡ n¶|	jdk�rš|	jdk�ršˆ|	j d ƒdu�sˆJ ‚ˆ|	j d ƒ|	_3nt‡fdd„|	j4D ƒ}t.|ƒdk�rÀ�q&tdd„ |D ƒƒ�rØJ ‚t5|ƒ}|d |	_6|dd… D ]}ˆ 7|d |¡ �qö�q&t8‡ fd d„ƒ}ˆ jD ]r}	t9|	d!ƒ�rP|ˆ :|	j6¡ j ;|	¡ t9|	d"ƒ�rt|ˆ :|	j1¡ j< ;|	¡ t9|	d#ƒ�r(|ˆ :|	j3¡ j= ;|	¡ �q(| >¡ D ]P}||ƒ�s¤|j<|j= D ]$}	|	j d }|	 )|¡ ˆ  -|	¡ �q¾t?|j||ƒ �q¤d}ˆ jD ]&}	|	jdk�s|	jdk�r |d7 }�q t@ Ad$|› �¡ ˆ  B¡  t
 | ˆ ¡}|S )%a  
    Performs a set of optimization passes to optimize a model for the
    purposes of inference. Specifically, the passes that are run are:
    1. Conv/BN fusion
    2. Dropout removal
    3. MKL layout optimizations

    The third optimization takes a function `use_mkl_heuristic` that's used
    to determine whether a subgraph should be explicity run in MKL layout.

    Note: As FX does not currently handle aliasing, this pass currently
    assumes nothing aliases. If that isn't true, use at your own risk.
    TÚ	heuristic)Úconv_bn_fuserN   Úmkldnn_layout_optimizeNr™   rN   rš   Fz+mkldnn_layout_optimize config is not a dictz4Heuristic not found in mkldnn_layout_optimize configc                   @   s   e Zd ZdZdZdZdS )z*optimize_for_inference.<locals>.MklSupportr   r‰   é   N)rH   rI   rJ   ÚNOÚYESÚUNKNOWNr   r   r   r   Ú
MklSupport  s   rŸ   r   z)this pass is only for torch.float modulesÚcpuz!this pass is only for CPU modulesÚcall_functionc                 S   s   g | ]}|j d k‘qS r|   )r   )rW   Úargr   r   r   rY   1  rV   z*optimize_for_inference.<locals>.<listcomp>c                    s   ˆ   d| f¡S )Nr€   )Úcall_method©rŽ   rk   r   r   rU   4  rV   z(optimize_for_inference.<locals>.<lambda>r£   r}   r   r€   c                    s0   t | dƒrˆ  | j¡S t | dƒr,ˆ  | j¡S d S )NÚcolorÚstart_color)Úhasattrr‘   r¥   r¦   r¤   )Úufr   r   Ú	get_colorQ  s
    

z)optimize_for_inference.<locals>.get_colorc                    s,   g | ]$}t |tjƒrˆ |ƒd urˆ |ƒ‘qS r,   )r"   r#   r$   r~   )r©   r   r   rY   l  rV   c                 s   s   | ]}|d u V  qd S r,   r   r~   r   r   r   Ú	<genexpr>p  rV   z)optimize_for_inference.<locals>.<genexpr>r   c                      s   t ˆ ƒS r,   )rj   r   rk   r   r   rU   w  rV   r¥   r¦   Ú	end_colorzmkldnn conversions: )CrŠ   ÚupdaterB   rN   r"   r7   ÚRuntimeErrorÚtracer4   r5   r#   r=   Úrootr8   r   Úlistr(   rœ   r%   r   r'   Úmkldnn_supportedr�   ÚnextÚ
parametersZdtyperM   rd   ZdeviceÚmkldnn_supported_unknownrž   Úanyr    Zinserting_beforeZmap_argr   r   r   r   Zinserting_afterZcreate_noder;   rh   rf   r:   r<   r   r‹   Ú	enumerater¦   r�   r«   Zall_input_nodesÚsortedr¥   r•   r   r§   r‘   Úappendrm   rn   Úvaluesri   ÚloggingÚinfor\   )r0   r–   r—   Zdefault_pass_configr†   Z
cur_tracerr?   r   rŸ   r   Zsupports_mkldnnrg   Zsample_parameterZmkldnn_argsZdense_xrf   Zprv_noder:   ÚuserZ	num_nodesZcur_idxZ
cur_colorsZother_colorZmkldnn_graphsr9   ZprvZmkldnn_conversionsÚresultr   )rl   r©   r¨   r   Úoptimize_for_inferenceê   sÌ    ý
	


6
*










r¾   )F)rp   r   )IZtorch.fxr#   Ztorch.fx.noder   r   Ztorch.nn.utils.fusionr   Útypingr   r   r   r   r	   r
   r   r   rM   Ztorch.nnr1   Ztorch.nn.functionalZ
functionalÚFZtorch.fx.passes.shape_propr   r4   Úcollectionsr   Ztorch.utils.mkldnnÚutilsZmkldnnr`   Úoperatorru   rº   Úenumr   r&   r   r$   r*   re   r/   rB   rN   r_   r2   ZLinearr3   ZReLUZ	MaxPool2dZ	AvgPool2dZAdaptiveAvgPool2dZreluZ	transposeZsigmoidZ
avg_pool2dZadaptive_avg_pool2dr±   ÚaddÚmulr´   ZMkldnnConv2dZMkldnnLinearrc   rh   ri   rj   rˆ   r‡   rŠ   r‹   ZTracerr¾   r   r   r   r   Ú<module>   sV   (	  (ý	
ý .
&ýü