o
    °ƒðj.  ã                   @  s>   d dl mZ d dlmZ d dlZddlmZ G dd„ dƒZdS )é    )Úannotations)ÚdequeNé   )Ú	ONNXModelc                   @  sê   e Zd ZdZdTdd„ZdUdd„ZdVdd„Zdd„ ZedWdd„ƒZ	edXdd„ƒZ
edYd#d$„ƒZedZd&d'„ƒZd[d(d)„Zd\d]d.d/„Zd\d^d0d1„Zd_d4d5„Zd6g fd`d;d<„Zd6d6g d6fdadBdC„Z	6	6	6dbdcdGdH„ZdddLdM„Z	6	NdedfdRdS„Zd6S )gÚFusionz!
    Base class for fusions.
    Úmodelr   Úfused_op_typeÚstrÚsearch_op_typec                 C  s>   || _ || _|| _g | _g | _| jd | j  d | _d | _d S )NÚ_fused_Ú_)r
   r   r   Únodes_to_removeÚnodes_to_addÚ_new_node_name_prefixÚ_new_node_name_suffix)Úselfr   r   r
   © r   ú©/tmp/claude-1000/-var-www-html-academy/3f42efd1-c2b7-4d08-9b05-30d86bb35479/scratchpad/piper/venv/lib/python3.10/site-packages/onnxruntime/quantization/fusions/fusion.pyÚ__init__   s   
zFusion.__init__Únodeúonnx.NodeProtoÚinput_name_to_nodesúdict[str, list[onnx.NodeProto]]Úoutput_name_to_nodeúdict[str, onnx.NodeProto]c                 C  s   t ‚)z…
        Interface function for derived fusion classes. Tries to fuse a node sequence containing
        the specified node.
        )ÚNotImplementedError)r   r   r   r   r   r   r   Úfuse   s   
zFusion.fuseÚreturnÚboolc                 C  s|   | j  ¡ }| j  ¡ }| j  ¡ D ]}|j| jkr|  |||¡ q| j  | j¡ | j  	| j
¡ t| jp3| j
ƒ}|r<| j  ¡  |S )z?
        Apply graph fusion on the entire model graph.
        )r   r   r   ÚnodesÚop_typer
   r   Úremove_nodesr   Ú	add_nodesr   r   Úremove_unused_constant)r   r   r   r   Úgraph_updatedr   r   r   Úapply*   s   

€
zFusion.applyc                 C  sF   | j }| jd u r| j |¡}|d | _|› | j›�}|  jd7  _|S )Né   )r   r   r   Úget_largest_node_name_suffix)r   ÚprefixÚlargest_suffixÚnew_namer   r   r   Úcreate_unique_node_name?   s   

zFusion.create_unique_node_namer   úlist[onnx.NodeProto]Úkeep_outputsú	list[str]c                 C  sL   | D ]!}|j D ]}||v rq||v r"|| D ]}|| vr!   dS qqqdS ©NFT)Úoutput)r   r-   r   r   Únode_to_removeÚoutput_to_removeÚimpacted_noder   r   r   Úis_safe_to_fuse_nodesK   s   

þ€ú	zFusion.is_safe_to_fuse_nodesÚattribute_namec                 C  s.   | j D ]}|j|krtj |¡}|  S qd S )N)Ú	attributeÚnameÚonnxÚhelperÚget_attribute_value)r   r5   ÚattrÚvaluer   r   r   Úget_node_attribute^   s   

þzFusion.get_node_attributeÚnode_outputÚ
child_nodeÚintc                 C  s(   t |jƒD ]\}}|| kr|  S qdS )Néÿÿÿÿ)Ú	enumerateÚinput)r>   r?   ÚindexÚ
input_namer   r   r   Úinput_indexf   s
   ÿzFusion.input_indexú	list[int]c                 C  sP   g }| j jD ]}| d¡r| |j¡ q| d¡r | |j¡ q| d¡ q|S )NÚ	dim_valueÚ	dim_paramú?)ÚshapeÚdimÚHasFieldÚappendrH   rI   )Útensor_typeÚ
shape_listÚdr   r   r   Útensor_shape_to_listm   s   

zFusion.tensor_shape_to_listc                 C  s8   t |jƒD ]\}}| j |¡}|d ur||f  S qdS )N©NN)rB   rC   r   Úget_constant_value)r   r   ÚiÚinpr<   r   r   r   Úget_constant_inputy   s   ÿzFusion.get_constant_inputç�íµ ÷Æ°>Úexpected_valueÚfloatÚdeltac                 C  s8   |   |¡\}}|d ur|jdkrt|| ƒ|k r|S dS )Nr&   rA   )rW   ÚsizeÚabs)r   r   rY   r[   rU   r<   r   r   r   Úfind_constant_input�   s   "zFusion.find_constant_inputc                 C  s   |   |||¡dkS ©Nr   )r^   )r   r   rY   r[   r   r   r   Úhas_constant_inputˆ   s   zFusion.has_constant_inputÚoutput_nameÚrankc                 C  s.   | j  |¡}|d u rdS t|jƒ|krdS dS r/   )r   rT   ÚlenrK   )r   ra   rb   r<   r   r   r   Úis_constant_with_specified_rank‹   s   z&Fusion.is_constant_with_specified_rankNÚparent_op_typeú dict[str, onnx.NodeProto] | NoneÚexcludeú(tuple[onnx.NodeProto | None, int | None]c                 C  sX   |du r	| j  ¡ }t|jƒD ]\}}||v r)|| }|j|kr)||vr)||f  S qdS )a  
        Find parent node based on constraints on op_type.

        Args:
            node: current node.
            parent_op_type (str): constraint of parent node op_type.
            output_name_to_node (dict): dictionary with output name as key, and node as value.
            exclude (list): list of nodes that are excluded (not allowed to match as parent).

        Returns:
            parent: The matched parent node. None if not found.
            index: The input index of matched parent node. None if not found.
        NrS   )r   r   rB   rC   r    )r   r   re   r   rg   rU   rV   Úparentr   r   r   Úmatch_first_parent•   s   
€zFusion.match_first_parentrF   ú
int | NoneÚreturn_indiceúlist[int] | Noneúonnx.NodeProto | Nonec           	      C  s¨   |dusJ ‚|du s|dksJ ‚|du r| j  ¡ }|du r2|  ||||¡\}}|dur0| |¡ |S |t|jƒkr;dS | j  |||¡}|durR|j|krR||vrR|S dS )a*  
        Find parent node based on constraints on op_type and index.
        When input_index is None, we will find the first parent node based on constraints,
        and return_indice will be appended the corresponding input index.

        Args:
            node (str): current node name.
            parent_op_type (str): constraint of parent node op_type.
            input_index (int or None): only check the parent given input index of current node.
            output_name_to_node (dict): dictionary with output name as key, and node as value.
            exclude (list): list of nodes that are excluded (not allowed to match as parent).
            return_indice (list): a list to append the input index when input_index is None.

        Returns:
            parent: The matched parent node.
        Nr   )r   r   rj   rN   rc   rC   Ú
get_parentr    )	r   r   re   rF   r   rg   rl   ri   rD   r   r   r   Úmatch_parent´   s   

zFusion.match_parentÚparent_op_typesÚparent_input_indexúlist[onnx.NodeProto] | Nonec              	   C  sŽ   |durt |ƒt |ƒksJ ‚|du r| j ¡ }|}g }t|ƒD ]%\}}	| j||	|dur/|| nd|g |d�}
|
du r= dS | |
¡ |
}q|S )aJ  
        Find a sequence of input edges based on constraints on parent op_type and index.
        When input_index is None, we will find the first parent node based on constraints,
        and return_indice will be appended the corresponding input index.

        Args:
            node (str): current node name.
            parent_op_types (str): constraint of parent node op_type of each input edge.
            parent_input_index (list): constraint of input index of each input edge. None means no constraint.
            output_name_to_node (dict): dictionary with output name as key, and node as value.
            return_indice (list): a list to append the input index
                                  When there is no constraint on input index of an edge.

        Returns:
            parents: a list of matched parent node.
        N)rg   rl   )rc   r   r   rB   rp   rN   )r   r   rq   rr   r   rl   Úcurrent_nodeÚmatched_parentsrU   r    Úmatched_parentr   r   r   Úmatch_parent_pathã   s(   
ú
zFusion.match_parent_pathÚpathsú!list[tuple[list[str], list[int]]]ú9tuple[int, list[onnx.NodeProto] | None, list[int] | None]c                 C  sF   t |ƒD ]\}}g }|  ||d |d ||¡}|r |||f  S qdS )z@
        Find a matching parent path to the given node.
        r   r&   )rA   NN)rB   rw   )r   r   rx   r   rU   Úpathrl   Úmatchedr   r   r   Úmatch_parent_paths  s   	ÿzFusion.match_parent_pathsTÚ
child_typeú&dict[str, list[onnx.NodeProto]] | NoneÚ	recursivec           	      C  sn   | j  ||¡}t|ƒ}t|ƒdkr5| ¡ }|j|kr|S |r/| j  ||¡}|D ]}| |¡ q't|ƒdksd S r_   )r   Úget_childrenr   rc   Úpopr    Ú
appendleft)	r   r   r~   r   r€   ÚchildrenÚdqrt   Úchildr   r   r   Úfind_first_child_by_type$  s   
ø
zFusion.find_first_child_by_type)r   r   r   r	   r
   r	   )r   r   r   r   r   r   )r   r   )
r   r,   r-   r.   r   r   r   r   r   r   )r   r   r5   r	   )r>   r	   r?   r   r   r@   )r   rG   )r   r   )rX   )r   r   rY   rZ   r[   rZ   r   r@   )r   r   rY   rZ   r[   rZ   r   r   )ra   r	   rb   r@   r   r   )
r   r   re   r	   r   rf   rg   r,   r   rh   )r   r   re   r	   rF   rk   r   rf   rg   r,   rl   rm   r   rn   )NNN)r   r   rq   r.   rr   rm   r   rf   rl   rm   r   rs   )r   r   rx   ry   r   r   r   rz   )NT)
r   r   r~   r	   r   r   r€   r   r   rn   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r%   r+   Ústaticmethodr4   r=   rF   rR   rW   r^   r`   rd   rj   rp   rw   r}   r‡   r   r   r   r   r      sD    





û#ù3ú
1ûr   )Ú
__future__r   Úcollectionsr   r8   Ú
onnx_modelr   r   r   r   r   r   Ú<module>   s
   