a
    Ž¥»aJ¿  ã                   @   s  d dl Z d dlZd dlZd dlmZ d dlmZmZ d dlm	Z	m
Z
 d dlmZ ddlmZmZ dd	lmZmZmZ dd
lmZmZmZ ddlmZ ddlmZmZ ddlmZ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-m.Z. ddl/m0Z0 ddl1m2Z2 d dl3m4Z4m5Z5 ddl%m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z= ddl>m?Z? ddl>m@Z@ d dlAmBZBmCZCmDZDmEZEmFZFmGZGmHZH e
eDeIe jJjKf eLdœdd„ZMe
eBeLdœdd„ZNe jJjOjPe jJjOjQe jJjOjRhZSdZTe
eBeLdœdd„ZUe
eDeIe jJjKf eDeIeBf eeGeDeIeBf eDeIeBf f d œd!d"„ZVe jJjKeDeCeCf dd#œd$d%„ZWeBeDeCeCf eBd&œd'd(„ZXeeBeBd)œd*d+„ZYe
e jZje jJjKeDeIe jJjKf e	e
d,œd-d.„Z[e
ee\e\eEe\ eEe\ eFe eDeIe jJjKf eDe
eLf eFe j] d/œ
d0d1„Z^eHe
eBf eee jJjKeDeIe jJjKf e	eDeIeBf eFe eDeIeBf ed2œ
d3d4„Z_e
ee jJjKeDeIe jJjKf e	eDeIeBf eFe eDeIeBf dd5œ	d6d7„Z`e
eBe jJjKeDeIe jJjKf e	eDeIeBf eLdd8œd9d:„Zae
e jJjKeDeIe jJjKf e	eDeIe!f eDeIeBf eBeFe eFe
 d;œ	d<d=„Zbe
eEe\ eDeIe j]f eDeIef e jJjKeDeIe jJjKf e	dd>œd?d@„Zce
e j]eDeIe j]f eDeIe!f ddAœdBdC„Zde	eDeIe j]f eDeIe!f ddDœdEdF„Zee
e jJjKeDeIe jJjKf eLdGœdHdI„Zfe
e jJjKeDeIe jJjKf dJœdKdL„Zge
eeDeIe jJjKf eDeIeBf dMœdNdO„ZheeDeIe jJjKf eDeIe!f eDeIef e	eDeIeBf eDeIeBf eEe\ eEe\ eFe
 dPœ
dQdR„Zie jJjKeDeIe jJjKf eBeDeIeBf ddSœdTdU„ZjeeDeIef eDeIeGeIekf f eDeef eDeIeBf eDeIeBf ddVœdWdX„Zld]eeBeDeIeGeIekf f eFeDeIeBf  eFeDeIeBf  eFeDeIeBf  eLedZœd[d\„ZmdS )^é    N)ÚGraphModule)Úpropagate_qconfig_ÚObserverBase)ÚGraphÚNode)ÚArgumenté   )Ú
QConfigAnyÚqconfig_equalsé   )Úconvert_dict_to_ordered_dictÚgenerate_qconfig_mapÚget_flattened_qconfig_dict)ÚQuantizeHandlerÚCustomModuleQuantizeHandlerÚStandaloneModuleQuantizeHandler)ÚPattern)Úis_equalization_observerÚnode_supports_equalization)ÚObservedGraphModuleÚObservedStandaloneGraphModule)ÚMatchResultÚ.get_default_output_activation_post_process_map)Úfind_matches)	Ú_parent_nameÚget_custom_module_class_keysÚall_node_args_have_no_tensorsÚassert_and_get_unique_deviceÚnode_bool_tensor_arg_indexesÚget_new_attr_name_with_prefixÚNON_QUANTIZABLE_WEIGHT_OPSÚWEIGHT_INDEX_DICTÚFUNCTIONAL_OPS_WITH_BIAS)ÚDEFAULT_OP_LIST_TO_FUSER_METHOD)Úget_default_qat_module_mappings)Úis_activation_post_processÚconvert)Úget_combined_dictÚget_qconfig_dtypesÚget_swapped_custom_module_classÚweight_is_quantizedÚ"activation_is_statically_quantizedÚactivation_is_int8_quantizedÚactivation_dtypeÚweight_dtype)Úget_fbgemm_backend_config_dict)Úvalidate_backend_config_dict)ÚAnyÚCallableÚDictÚListÚOptionalÚTupleÚUnion)ÚnodeÚmodulesÚreturnc                 C   s*   t | tjjƒo(| jdko(t|t| jƒ ƒS )NÚcall_module)Ú
isinstanceÚtorchZfxr   Úopr%   ÚstrÚtarget)r8   r9   © rA   úW/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/torch/quantization/fx/prepare.pyÚis_activation_post_process_node[   s    ÿrC   )r8   Úargr:   c                 C   s|   t | tƒrx| jdkrx| jtv rxt| jƒD ]$\}}||u r(|t| j v r( dS q(| j ¡ D ]\}}|dkrX||u rX dS qXdS )NÚcall_functionTÚweightF)	r<   r   r>   r@   r!   Ú	enumerateÚargsÚkwargsÚitems©r8   rD   ÚiZnode_argZ
kwarg_nameZkwarg_valuerA   rA   rB   Únode_arg_is_weight_   s    ÿ
ÿrM   c                 C   s‚   t | tƒr~| jdkr~| jtv rJt| jƒD ]\}}||u r(|tkr( dS q(n4| jtv r~| j	 
¡ D ]\}}|dkr^||u r^ dS q^dS )NrE   TZbiasF)r<   r   r>   r@   ÚCONV_OPS_WITH_BIASrG   rH   ÚCONV_BIAS_ARG_INDEXr"   rI   rJ   rK   rA   rA   rB   Únode_arg_is_biasr   s    


rP   )r8   r9   Úprepare_custom_config_dictÚqconfigr:   c                 C   s˜   || j  }| dg ¡}| dg ¡}dd„ |D ƒ}dd„ |D ƒ}| t|ƒd¡}	| | j |	¡}	|	d du rpd	|in|	d }
|	d
 du rˆi n|	d
 }|
|fS )z§
    Returns the standalone module qconfig_dict and prepare_config_dict
    for `node`, assuming that the module pointed to by `node` is
    a standalone modules.
    Ústandalone_module_nameÚstandalone_module_classc                 S   s"   i | ]}|d  |d |d f“qS ©r   r   r   rA   ©Ú.0ÚxrA   rA   rB   Ú
<dictcomp>Ž   ó    z1get_standalone_module_configs.<locals>.<dictcomp>c                 S   s"   i | ]}|d  |d |d f“qS rU   rA   rV   rA   rA   rB   rY   �   rZ   )NNr   NÚ r   )r@   ÚgetÚtype)r8   r9   rQ   rR   Ústandalone_moduleÚstandalone_module_name_configsÚstandalone_module_class_configsZclass_config_mapZname_config_mapÚconfigÚsm_qconfig_dictÚsm_prepare_config_dictrA   rA   rB   Úget_standalone_module_configs~   s    

ÿ
ÿrd   )ÚrootÚadditional_qat_module_mappingr:   c                 C   s    t tƒ |ƒ}t| |ddd� d S )NTF)ÚmappingZinplaceZremove_qconfig)r'   r$   r&   )re   rf   Zall_mappingsrA   rA   rB   Úqat_swap_modules–   s    ÿrh   )Úqconfig_dictrf   r:   c                 C   sJ   t tƒ |ƒ}|  dd¡}| ¡ }| ¡ D ]\}}||v r(|||| < q(| S )z³
    Update the qconfig_dict to account for module swaps during QAT.
    During QAT we perform a module swap on the nn.Module types to the corresponding nn.qat.modules types.
    Úobject_typeN)r'   r$   r\   ÚcopyrJ   )ri   rf   Zall_qat_mappingsÚobject_type_dictZnew_object_type_dictÚkÚvrA   rA   rB   Úupdate_qconfig_for_qat�   s    ÿro   )Úmodelri   r:   c           
      C   sÎ   |  dd¡}|du r|S t|  ¡ ƒ}| jjD ]œ}|jdkr,t|t|jƒ ƒ}|t	t
 ¡ ƒvr^q,t
 ¡ D ]`\}}||krf|  |d d¡}|D ]*}	t|  |	d¡|ƒsŠtdd|› d� ƒ‚qŠ|durf|||< qfq,|S )zR
    Update the qconfig_dict to account for fused modules such as LinearReLU.
    rj   Nr;   r   z+During fusion, we need to specify the same zqconfigs for both modules in Ú.)r\   ÚdictÚnamed_modulesÚgraphÚnodesr>   r]   r?   r@   Úlistr#   ÚvaluesrJ   r
   ÚLookupError)
rp   ri   rl   r9   r8   Úmodule_typeÚopsZfuserZfused_qconfigr>   rA   rA   rB   Úupdate_qconfig_for_fusion®   s(    

ÿr{   )r8   Úobserverrp   r9   rt   r:   c           
      C   s˜   t |ƒ}|r| |¡ t|ƒr*| jd }n
| jd }t|ƒ}||ƒ}t|||ƒ |||< | | ¡�" | d|| fi ¡}	W d  ƒ n1 sŠ0    Y  |	S )zp
    Attaches `observer` to `model`, and creates a node which calls
    `observer` on the output of `node`.
    Z_equalization_process_Z_activation_post_process_r;   N)r   Útor   Únamer   ÚsetattrZinserting_afterZcreate_node)
r8   r|   rp   r9   rt   Zmodel_deviceÚprefixZget_new_observer_nameZobserver_nameÚnew_obsrA   rA   rB   Úinsert_observerÑ   s    


ÿ"r‚   )
r8   rR   Úinputs_seen_counterÚoutputs_seen_counterÚinput_quantized_idxsÚoutput_quantized_idxsÚqhandlerr9   Úcache_for_no_tensor_checkr:   c	                 C   sê   | j dkr ||v rtjS tjS nÆ| j dv r¤t| ||ƒ}	|	r>dS | j dkoR| jtjk}
|
r^tjS |durœ|dur”| ¡ r”| 	|d¡r”t
|ƒ\}}}|S tjS qætjS nB| j dkr´tjS | j dkrÔ||v rÌtjS tjS ntd|  ¡ › �ƒ‚dS )	ay  
    Returns the expected dtype of the input and output of this node after
    convert. If the value is not None, it represents the dtype of the
    Tensor. If the value is None, it means the value is not a Tensor.

    Note: this is for activations only, weight dtypes are not handled here.

    TODO(future PR, if needed): explicitly spell out the non-Tensor
    dtypes.
    Úplaceholder)r;   Úcall_methodrE   NrE   FZget_attrÚoutputzneed to handle )r>   r=   Úquint8Úfloatr   r@   ÚoperatorÚgetitemZinput_output_observedZis_output_quantizedr(   ÚAssertionErrorZformat_node)r8   rR   rƒ   r„   r…   r†   r‡   r9   rˆ   Zargs_have_no_tensorsÚ
is_getitemZ	act_dtyper.   Zact_compute_dtyperA   rA   rB   Ú$get_target_activation_dtype_for_nodeí   s<    

ÿÿ

ÿÿ

r’   )
r8   rD   rR   rp   r9   rt   Únode_name_to_target_dtyper‡   rQ   r:   c	           $      C   sv  t |ttfƒrJg }	|D ]&}
t| |
|||||||ƒ	}|	 |¡ qt|ƒ|	ƒS t |tƒsX|S t |tƒsfJ ‚|}|duozt |tƒ}|�sLt| |ƒ}|dus˜J ‚|r¢|j	n|j
}t| |ƒ}|p¸| }|oÐt|ƒoÐ| jtv}|oðt|ƒtjkoðt|ƒtjk}||j }|| j }||k�o8|tjk�o8|tjdfv�o8|�o8t|ƒ}|�pH|�pH|}n�t| |||ƒ\}}| dg ¡}d}t| jƒD ]\}}||u �rx|} �q˜�qx|du �r¨d}n4||j }||v �rÂtjntj}||k�oÚ|tjk}|�rr|ƒ }d}|j ¡ D ]L\} }!| jdk�rö|| j }"t|"ƒt|ƒk�rö|| j |k�rö| } �qD�qö|du �rnt|||||ƒ}#|||#j< |#}n|}|S )zk
    Given a `node` and an `arg`, inserts an input observer between
    `node` and `arg` if necessary.
    Nr…   Fr;   ) r<   rv   ÚtupleÚ,maybe_insert_input_observer_for_arg_or_kwargÚappendr]   r   r   rM   rF   Ú
activationrP   r*   r@   r    r-   r=   Úfloat16r.   r~   r�   Úboolr+   rd   r\   rG   rH   rŒ   ÚusersrJ   r>   r‚   )$r8   rD   rR   rp   r9   rt   r“   r‡   rQ   Znew_arg_to_returnZ	inner_argZnew_inner_argÚnew_argÚis_standalone_moduleÚ	is_weightÚact_post_process_ctrZis_biasZis_activationZweight_needs_obsZbias_needs_obsZ	arg_dtypeZ
node_dtypeZ(dtype_changes_and_second_dtype_not_floatZ	needs_obsZ_sm_qconfig_dictrc   Zsm_input_quantized_idxsZcur_input_idxZarg_idxZarg_to_checkZnew_obs_modZexisting_obs_nodeZmaybe_obs_nodeÚ_Zmaybe_obs_modZnew_obs_noderA   rA   rB   r•   0  s¦    
ý
ÿ

ÿ

þ


ûùöÿý	ÿÿ
ÿ



ÿ
þ
ÿþ


ÿ
r•   )	r8   rR   rp   r9   rt   r“   r‡   rQ   r:   c                 C   s–   |du rdS |dusJ ‚g }| j D ]&}	t| |	|||||||ƒ	}
| |
¡ q"i }| j ¡ D ](\}}t| ||||||||ƒ	}|||< qXt|ƒ| _ || _dS )a
  
    If needed, inserts observers to the input args and kwargs of `node`.
    Note: modifies `node` inplace.

    For example, if cur_node needs an observer after prev_node, we change from

      prev_node -> cur_node

    To

      prev_node -> obs -> cur_node
    N)rH   r•   r–   rI   rJ   r”   )r8   rR   rp   r9   rt   r“   r‡   rQ   Únew_argsrD   r›   Z
new_kwargsrm   ÚkwargZ	new_kwargrA   rA   rB   Ú%maybe_insert_input_observers_for_node´  s*    
ýý

r¢   )r8   Úequalization_qconfigrp   r9   rt   r“   Ú	is_branchr:   c                 C   s¸   |du st | |ƒsdS |r0t d| › d�¡ dS g }| jD ]n}t|tƒrRt| |ƒr^| |¡ q:t| |ƒ}	|	rr|j	n|j
}
|
ƒ }t|||||ƒ}||j ||j< | |¡ q:t|ƒ| _dS )zâ
    If `node` needs to be equalized, find the input/weight observers it needs in
    `equalization_qconfig`, creates them, and inserts it into `graph`.

    If `node` does not need an equalization observer, returns None.
    NzCannot equalize z  because it is part of a branch.)r   ÚwarningsÚwarnrH   r<   r   rP   r–   rM   rF   Zinput_activationr‚   r~   r”   )r8   r£   rp   r9   rt   r“   r¤   r    rD   r�   Zact_eq_process_ctrZnew_eq_obs_modZnew_eq_obs_noderA   rA   rB   Ú2maybe_insert_input_equalization_observers_for_nodeæ  s.    
ÿ



ÿ
ÿr§   )	r8   rp   r9   rt   Úmatchesr“   Úmatched_patternr‡   r:   c                 C   sæ   |  | jd¡\}}	}
}}|du r$dS |dus0J ‚| jdksBJ dƒ‚|duoRt|tƒ}|| j }| ||j¡o||tjdtj	fv}|oˆt
|ƒ}|o’| }|rÞ|j}t|ƒr´tƒ   ||¡}|ƒ }t| ||||ƒ}|| j ||j< |S dS dS )z¤
    If `node` needs an output observer, creates it, inserts it into `graph`
    and returns it.

    If `node` does not need an output observer, returns None.
    ©NNNNNNr‹   z3observer insertion for outputs is handled elsewhere)r\   r~   r>   r<   r   Z!should_insert_observer_for_outputÚtrainingr=   r™   r�   r+   r—   r,   r   r‚   )r8   rp   r9   rt   r¨   r“   r©   r‡   Ú	root_nodeÚmatched_nodesÚpatternrR   rœ   ÚdtypeZshould_insert_observerrž   r|   r�   rA   rA   rB   Ú%maybe_insert_output_observer_for_node  sH    ÿÿ
ÿþÿÿþÿÿr°   )Úgraph_output_noder†   r“   Úqconfig_maprp   r9   rt   r:   c           
         s¤   |dgks|g ksJ dƒ‚|g kr&dS t j}tt jttt jf tttf t jjttt jjf t	tdœ‡ fdd„‰ g }| j
D ]}	| ˆ |	||||||ƒ¡ qz|| _
dS )zž
    If the output needs to be quantized and there are any nodes
    in the output which are not already observed, inserts observers
    for those nodes.
    r   z,unrecognized format of output_quantized_idxsN)Ú
maybe_nodeÚtarget_dtyper“   r²   rp   r9   rt   r:   c                    sì   t | tƒrZ|| j }||krT| | j¡}|dus8J dƒ‚| ¡ }	t| |	|||ƒ}
|
S | S nŽt | ttfƒr¨g }| D ]}| ˆ |||||||ƒ¡ qpt | tƒrž|S t|ƒS n@t | t	ƒräi }|  
¡ D ] \}}ˆ |||||||ƒ||< q¾|S |S dS )a`  
        Navigate an arbitrary data structure of lists, tuples, dicts.
        For each container type, recurse on all inputs. Once any Node
        is found, insert an observer if needed and do not recurse further.

        For example, given a structure of

          {'foo1': [[bar1]], 'foo2': {'foo3': [[[bar3]]]}}

        we recurse down to bar1 and bar3, observe them if necessary,
        and if we inserted an observer then replace the original node
        with its observer.

        Returns the data structure with all nodes needing observation being
        replaced by their observers.
        Nz=Quantizing the output node without a qconfig is not supported)r<   r   r~   r\   r—   r‚   rv   r”   r–   rr   rJ   )r³   r´   r“   r²   rp   r9   rt   Úthis_node_dtyperR   Zobserver_modZobserver_nodeÚresultsZ
inner_nodeZresults_dictrm   Zinner_v©Ú&_recursive_maybe_replace_node_with_obsrA   rB   r¸   l  s@    


ÿ
ÿþ


þ
zZmaybe_insert_observers_before_graph_output.<locals>._recursive_maybe_replace_node_with_obs)r=   rŒ   r   r¯   r3   r?   r	   ÚnnÚModuler   rH   r–   )
r±   r†   r“   r²   rp   r9   rt   Zoutput_target_dtyper    Zold_argrA   r·   rB   Ú*maybe_insert_observers_before_graph_outputO  s0    ÿ
ø=
þÿr»   )r8   r´   r“   r¨   r:   c           
      C   sX   ||| j < | | j d¡\}}}}}|durT| ¡ rT| jd }	t|	tƒrTt|	|||ƒ dS )a  
    Assigns `target_dtype` to `node`. If `node` is a general tensor shape op
    (see GeneralTensorShapeOpQuantizeHandler in quantization_patterns.py for more details)
    also call this function recursively on
    the first argument, to propagate the dtype to the caller.
    rª   Nr   )r~   r\   Úis_general_tensor_shape_oprH   r<   r   Úmaybe_propagate_dtype_for_node)
r8   r´   r“   r¨   r¬   r­   r®   r‡   rR   Z	prev_noderA   rA   rB   r½   ³  s    
ÿ

ÿr½   )rt   r“   r¨   r:   c                 C   s<   | j D ]0}t|ƒ}|D ]}|j| }t|tj||ƒ qqdS )a  
    Currently we assume that inputs to the graph are either `torch.float` or
    `torch.quint8`, which is not always correct. For ops such as
    `x.masked_fill(mask, value)`, we know that the dtype of  `mask` is a
    `BoolTensor`. Propagate this information throughout the graph.

    Note: not all dtypes in the graph will be correct after this pass, but a
    higher percentage of them will be correct. Hopefully in the future we can
    replace this with a better way to reason about dtypes of tensors.
    N)ru   r   rH   r½   r=   r™   )rt   r“   r¨   r8   Zbool_arg_idxsZbool_arg_idxZcur_noderA   rA   rB   Ú propagate_dtypes_for_known_nodesÉ  s    


ÿr¾   )r8   rp   r9   r:   c                 C   sö  d}t t| jƒƒD ](}t| j| tttfƒr| j| } q<q|du rHdS t|ttfƒr`|d }nt|tƒrp|}ndS d}t||ƒsøt|tƒs�dS |jdkrždS d}t t|jƒƒD ]}|j| }t|tƒr° qÎq°|du rÚdS |}|d7 }|dkrxt	dƒ‚qxt|tƒ�sJ ‚|j
}t|tƒ�sJ ‚|| }	t|ttfƒ�r®t|ƒD ]n\}
}|
dk�rT�q>d}t||ƒ�sŒ|jd }|d7 }|dk�rXt	dƒ‚�qXt|j
ƒ\}}t|| ||	ƒ �q>| j ¡ D ]8\}}t||ƒ�sÐJ ‚t|j
ƒ\}}t|| ||	ƒ �q¸dS )	aª  
    Ensures that we share an observer
    for all input arguments as well as the output argument. In detail, given
    a graph of

      x0 -> obs0 -> op -> x2
                  /
      x1 -> obs1 /

    where node obs0 points to observer instance observer0,
    obs1 points to observer1 and obs2 points to observer2, we make nodes obs1
    and ob2 point to observer0.
    Returns: whether the operation succeeded or not
    NFr   r‰   r   i'  z(Unable to find observer of previous nodeT)ÚrangeÚlenrH   r<   r   rv   r”   rC   r>   r�   r@   r?   rG   r   r   rš   rJ   )r8   rp   r9   Z	first_argrL   Zfirst_arg_argZiteration_guardZtrace_back_nodeZtarget_to_useZobs_mod_to_useZ	input_idxZ	input_argÚparent_namer~   Úoutput_obs_noderŸ   rA   rA   rB   Ú'maybe_make_input_output_share_observersß  sd    











rÃ   )r8   rp   r9   c                 C   sD   t | j ¡ ƒ}|D ],\}}t||ƒs(J ‚| | ¡ |j |¡ qd S ©N)rv   rš   rJ   rC   Zreplace_all_uses_withrt   Z
erase_node)r8   rp   r9   rJ   rÂ   rŸ   rA   rA   rB   Úremove_output_observer9  s
    
rÅ   )r8   rR   r9   rQ   c           
      C   sN   || j  }| di ¡}t|||ƒ}| |¡}t| j ƒ\}}	t|| |	|ƒ d S )NÚ%float_to_observed_custom_module_class)r@   r\   r)   Ú
from_floatr   r   )
r8   rR   r9   rQ   Zcustom_moduleZcustom_module_class_mappingZobserved_custom_module_classZobserved_custom_modulerÁ   r~   rA   rA   rB   Úswap_custom_module_to_observedC  s    
ÿÿÿÿrÈ   )
rp   r9   r¨   r²   rt   rQ   Úequalization_config_mapr…   r†   r:   c	           #      C   s
  i }	t ƒ }
d}d}d}t | jdd�ƒ}| jjD ]:}| |jd¡\}}}}}t|||||||||
ƒ	|	|j< q.t| j|	|ƒ t| jjƒ}|D �]z}|j	dkrœ�n<|j	dv �rØ| |jd¡\}}}}}| |jd¡}|	|j }|du }|j	dkoô|j
tjk}|du �s|�s|�o|j	d	k }|�sØt | jdd�ƒ}|j	d	k�rÄd}t|jƒdk�rÒt|jd tƒ�rÒt|jd jƒd
k�rÒ|jd jD ]N}| |jd¡du�p¸|j	dk�o¸t|t|j
ƒ tƒ}||k�r‚|�r‚d}�q‚t||| |||	||ƒ t||| |||	|ƒ ||u }|du�o| ¡ }|du�o&| ¡ }|�rØ|�sØt|| ||||	||ƒ} | du�rØt|j ¡ ƒ}!|!D ] }"|"| u �rx�qf|" || ¡ �qf|�r¨t|| |ƒ�s¨t|| |ƒ t|tƒ�rØt||||ƒ nt|||	|| ||ƒ |j	dk�rî|d
7 }qˆ|j	d	krˆ|d
7 }|}qˆ|S )a$  
    Inserts observers, using the following high level algorithm:

    For each node in the graph:
      1. determine the target dtype of this node in the quantized graph, and save
           it for future steps
      2. determine the target dtype or all args and kwargs of this node
      3. if any arg or kwarg's target dtype does not match the current node's
           dtype, insert an observer
      4. if the current node needs an output observer, insert it

    For example:

    - starting graph:
        x0 -> linear -> x1

    - observed graph after processing x0:
        x0(fp32)

    - observed graph after processing linear:
        x0(fp32) -> x0_obs0(int8) -> linear(int8) -> linear_obs0(int8)

    - observed graph after processing x1:
        x0(fp32) -> x0_obs0(int8) -> linear(int8) -> linear_obs0(int8) -> x1

    After a node is processed, the naive observer placement is guaranteed to be
    complete for that node and all of its predecessors. There can be future
    passes which optimize the graph by deduplicating observers, etc.
    r   NF)Zremove_duplicaterª   r‰   )r;   rŠ   rE   r‹   rE   r‹   r   r;   T) rr   rs   rt   ru   r\   r~   r’   r¾   rv   r>   r@   rŽ   r�   rÀ   rH   r<   r   rš   r?   r   r¢   r§   Úis_general_tensor_value_opr¼   r°   ÚkeysZreplace_input_withrÃ   rÅ   r   rÈ   r»   )#rp   r9   r¨   r²   rt   rQ   rÉ   r…   r†   r“   rˆ   rƒ   r„   Zresults_noder8   r¬   r­   r®   r‡   rR   Znodes_before_observationr£   rµ   Zoutput_not_a_tensorr‘   Zskip_inserting_observersZis_quantized_branchÚuserZis_user_quantizedZis_last_node_of_patternrÊ   r¼   Zmaybe_output_obs_nodeZ
orig_usersZ	user_noderA   rA   rB   Úinsert_observers_for_modelS  sÀ    )ÿý	ÿ


ÿ


ÿ
ÿý
üÿþýþ
ý
þÿÿ
þ

ý

rÍ   )rp   r9   r¨   rQ   r:   c                 C   s°   |  ¡ D ]¢\}\}}}}}	|du r&qnt|tƒs2qt||||	ƒ\}
}||j }tjjj}|||
|ƒ}t	| 
dg ¡ƒ}t||j|ƒ}t|jƒ\}}t|| ||ƒ |||j< qdS )z¨
    Runs prepare_fx on each standalone module. Note: this does
    not modify the graph, it just replaces the unobserved modules with
    their observed versions.
    NÚpreserved_attributes)rJ   r<   r   rd   r@   r=   ÚquantizationZquantize_fxZ_prepare_standalone_module_fxÚsetr\   r   rt   r   r   )rp   r9   r¨   rQ   Z	node_namer¬   r­   r®   r‡   rR   rb   rc   r^   ÚprepareZobserved_standalone_modulerÎ   rÁ   r~   rA   rA   rB   Ú$run_prepare_fx_on_standalone_modules#  s8    ý
ÿÿ
ÿ
ÿÿþ
ÿrÒ   )Úobservedr²   Únode_name_to_scopeÚpatternsrQ   Úequalization_qconfig_mapr:   c                 C   s"   || _ || _|| _|| _|| _d S rÄ   )Z	_patternsZ_qconfig_mapZ_prepare_custom_config_dictZ_node_name_to_scopeZ_equalization_qconfig_map)rÓ   r²   rÔ   rÕ   rQ   rÖ   rA   rA   rB   Ú
save_stateJ  s    ÿr×   F)rp   ri   rÔ   rQ   Úequalization_qconfig_dictÚbackend_config_dictrœ   r:   c              
   C   sæ  |du ri }|du ri }|du r&t ƒ }t|ƒ | di ¡}|d }t||ƒ}	t|ƒ t|ƒ t|ƒ}
t| |
ƒ | jr”| di ¡}t| |ƒ t	||ƒ}t
| |ƒ}t
| |ƒ}t|  ¡ ƒ}t| || j||ƒ}t| || j||ƒ}| dg ¡}| dg ¡}dd„ |D ƒ}d	d„ |D ƒ}t|d
ƒ}t| j||	||||ƒ}| dg ¡}| dg ¡}t| |||ƒ t| |||| j||||ƒ	}t| |||	||ƒ t| dg ¡ƒ}t| | j|ƒ} |�râ|du�s°J ‚t|jd tƒ�sÊJ dƒ‚t |¡| _t |¡| _| S )aQ   standalone_module means it a submodule that is not inlined in
    parent module, and will be quantized separately as one unit.

    How the standalone module is observed is specified by `input_quantized_idxs` and
    `output_quantized_idxs` in the prepare_custom_config for the standalone module
    Args:
        node_name_to_scope: mapping from node name to the scope of the module which contains the node.
        The scope is a tuple of fully qualified path of the module and the type of the module
    Returns:
        model(GraphModule): prepared standalone module
        attributes:
            _standalone_module_input_quantized_idxs(List[Int]): a list of
                indexes for the graph input that is expected to be quantized,
                same as input_quantized_idxs configuration provided
                for the standalone module
            _standalone_module_output_quantized_idxs(List[Int]): a list of
                indexs for the graph output that is quantized
                same as input_quantized_idxs configuration provided
                for the standalone module
    NZadditional_quant_patternÚquant_patternsrf   rS   rT   c                 S   s   g | ]}|d  ‘qS ©r   rA   ©rW   ra   rA   rA   rB   Ú
<listcomp>°  rZ   zprepare.<locals>.<listcomp>c                 S   s   g | ]}|d  ‘qS rÛ   rA   rÜ   rA   rA   rB   rÝ   ±  rZ   rÆ   r…   r†   rÎ   r   zVstandalone module only supports returning simple value currently(not tuple, dict etc.))r/   r0   r\   r'   r   r   r   r«   rh   ro   r{   rr   rs   r   rt   r   r   rÒ   rÍ   r×   rÐ   r   r<   rH   r   r=   ZtensorZ'_standalone_module_input_quantized_idxsZ(_standalone_module_output_quantized_idxs)rp   ri   rÔ   rQ   rØ   rÙ   rœ   Zadditional_quant_patternsrÚ   rÕ   Zflattened_qconfig_dictrf   r9   rÖ   r²   r_   r`   Zstandalone_module_namesZstandalone_module_classesZcustom_module_classesr¨   r…   r†   Zresult_noderÎ   rA   rA   rB   rÑ   Y  s�    
ÿÿ
ÿ



	ÿÿÿþÿÿÿü
ÿÿÿrÑ   )NNNF)nr=   rŽ   r¥   Ztorch.fxr   Ztorch.quantizationr   r   Ztorch.fx.graphr   r   Ztorch.fx.noder   rR   r	   r
   Zqconfig_utilsr   r   r   Zquantization_patternsr   r   r   Zquantization_typesr   Z	_equalizer   r   Zgraph_moduler   r   Zpattern_utilsr   r   Zmatch_utilsr   Úutilsr   r   r   r   r   r   r    r!   r"   Zfuser_method_mappingsr#   Zquantization_mappingsr$   Ztorch.ao.quantization.quantizer%   r&   r'   r(   r)   r*   r+   r,   r-   r.   rÙ   r/   r0   Útypingr1   r2   r3   r4   r5   r6   r7   r?   r¹   rº   r™   rC   rM   Z
functionalZconv1dZconv2dZconv3drN   rO   rP   rd   rh   ro   r{   rÏ   r‚   Úintr¯   r’   r•   r¢   r§   r°   r»   r½   r¾   rÃ   rÅ   rÈ   rÍ   rÒ   r]   r×   rÑ   rA   rA   rA   rB   Ú<module>   sf  ,($ý
ûþ
ýý$ú
öD


ö 

÷3
ø0

÷;
øe
û
üü[ý
ü



ö R
û(



ù    ùù