3
I4W^  ã               @   sL   d dl mZmZmZmZ d dlmZ d dljj	Z
d dlmZmZ dd„ ZdS )é    )Úabsolute_importÚdivisionÚprint_functionÚunicode_literals)ÚdefaultdictN)ÚcoreÚutilsc             C   s²  i }t dd„ ƒ}| j}dd„ | jD ƒ}�xô|D �]ê}|jƒ oD|jdkr.tj|jjj	ƒ}d|krl|d dkrlq.dd„ |j
D ƒ}t|ƒd	ks�td
ƒ‚dd„ |jD ƒ}t|ƒdks´tdƒ‚x|D ]}	| j|	|ƒ qºW x|D ]}
| j||
ƒ qÔW xftd	ƒD ]Z}| j|| jƒ}|jtjdƒƒ}| j|| |ƒ | j||ƒ |||  j|ƒ |||< qòW xftt|ƒƒD ]V}| j|| jƒ}|jtjdƒƒ}| j||| ƒ | j||ƒ |||| < |||< �q^W d|d< | jtjdg g f|Žƒ}x|D ]}	| j|	|ƒ �qÞW x|D ]}
| j||
ƒ �qúW | j|ƒ q.W xŽ|D ]†}||k�r<|| }n&|| }|d jd }|dd… ||< xD|| D ]8}x&|jD ]}| j||ƒ | j|ƒ �qxW | j|ƒ �qlW �q$W dS )z¹
    Convert all Convolutions operators which are in the NCHW order
    to NHWC order and also transform their inputs and outputs so that the
    rest of the graph is not affected.
    c               S   s   g S )N© r	   r	   r	   úI/tmp/pip-build-e66j97b2/torch/caffe2/python/nomnigraph_transformations.pyÚ<lambda>   s    z#transpose_network.<locals>.<lambda>c             S   s   g | ]}|‘qS r	   r	   )Ú.0Úxr	   r	   r
   ú
<listcomp>   s    z%transpose_network.<locals>.<listcomp>ZConvÚorderZNCHWc             S   s   g | ]}|‘qS r	   r	   )r   r   r	   r	   r
   r      s    é   z$Conv operator should have two inputsc             S   s   g | ]}|‘qS r	   r	   )r   r   r	   r	   r
   r      s    é   z#Conv operator should have an outputZ	NCHW2NHWCZ	NHWC2NCHWZNHWCr   N)r   ZdataFlowZnodesZ
isOperatorÚnamer   Z
ArgsToDictÚ
annotationZoperator_defÚargÚinputsÚlenÚAssertionErrorÚoutputsZ
deleteEdgeÚrangeZcreateUniqueDataNodeZ
createNodeÚngZNeuralNetOperatorZ
createEdgeÚappendr   ZCreateOperatorZ
deleteNodeZreplaceAllUsesWith)ÚnnÚincomingÚoutgoingZdfgZ
orig_nodesÚnodeZarg_dictr   r   ÚinpZoutpÚidxZnew_inpZtranspZnew_outpÚnew_nodeZorig_tensorZ
new_tensorZout_opsZopnodeÚoutr	   r	   r
   Útranspose_network	   sd    






r$   )Ú
__future__r   r   r   r   Úcollectionsr   Zcaffe2.python.nomnigraphÚpythonZ
nomnigraphr   Zcaffe2.pythonr   r   r$   r	   r	   r	   r
   Ú<module>   s   