a
    Ž¥»aÚP  ã                   @   s  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 d dl	m
Z
mZ d dlmZ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Zejjjdgejjjdgejjjdgejjjdgejjjdgejjj dgejjj!d	giZ"ejjjejjj ejjj!hZ#ejjjejjjejjj ejjj!hZ$d
d„ Z%d@e&dœdd„Z'dd„ Z(eee&eee&f ee&ef f dœdd„Z)eejj*eee&ejj*f eee&ee&e+f f e,edœdd„Z-ee dœdd„Z.dd„ Z/eedœdd„Z0ee,edœd d!„Z1e&ed"œd#d$„Z2eeee  d%œd&d'„Z3e
ee e
d(œd)d*„Z4ejj*ed+œd,d-„Z5ejj*ee&eed.œd/d0„Z6e&eeee&ejj*f eee&ee&e+f f eeef d1œd2d3„Z7eee&ejj*f eee,f e,d4œd5d6„Z8ee,d%œd7d8„Z9eee: d%œd9d:„Z;ee,d%œd;d<„Z<dAeee&ej*f eej* eee d=œd>d?„Z=dS )Bé    Né   )Úis_per_tensorÚis_per_channel)Úis_activation_post_process)ÚGraphModuleÚmap_arg)ÚGraphÚNode)	ÚCallableÚOptionalÚListÚDictÚAnyÚSetÚTupleÚUnionÚTypeé   é   c                 C   s8   |   dd¡}t|ƒdkr$d|d fS |d |d fS d S )NÚ.r   Ú r   )ÚrsplitÚlen)ÚtargetÚr© r   úU/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/torch/quantization/fx/utils.pyÚ_parent_name&   s    r   T)Úreturnc                 C   s¢  t  d¡}t  d¡}ddddddœ}i }d	}|D ]}t|ƒ||< q0g }| jD �]}	t|	jƒ}
|rl|
 d
d¡}
t|	jƒ}|rŠ||v rŠ|| }t|	jƒ}|rä| 	|¡}|r¸d| 
d¡› d�}| 	|¡}|rØd| 
d¡› d�}| d
d¡}t|	jƒ}|rþ| d
d¡}t|	jƒ}t||
||||fƒD ] \}}t|| t|ƒƒ||< �q| |
||||g¡ qLd}d}||j|i |¤Ž7 }|D ]}||j|i |¤Ž7 }�qt|�rž|d7 }|S )zyReturns a printable representation of the ops in the graph of g.
    If shorten is True, tries to abbreviate fields.
    z<built-in function (.*)>z <built-in method (.*) of type.*>ZplchdrZgt_prmZcl_funZcl_modZcl_meth)ÚplaceholderÚget_attrÚcall_functionÚcall_moduleÚcall_method)ÚnameÚopr   ÚargsÚkwargsÚactivation_post_processZobsz<bi_fun r   ú>z	<bi_meth r   z9{:<{name}} {:<{op}} {:<{target}} {:<{args}} {:<{kwargs}}
z'*obs_{n} = activation_post_process_{n}
)ÚreÚcompiler   ÚnodesÚstrr$   Úreplacer%   r   ÚsearchÚgroupr&   r'   ÚzipÚmaxÚappendÚformat)ÚgÚshortenZbuilt_in_func_reZbuilt_in_meth_reZop_dictZmax_lensZ	col_namesÚsÚresultsÚnr$   r%   r   Zbuilt_in_funcZbuilt_in_methr&   r'   ÚkÚvÚres_strZ
format_strÚresultr   r   r   Úgraph_pretty_str-   sX    

û






r>   c                 C   s>   t | jƒsJ dƒ‚|  ¡ \}}t|ƒ}t|ƒ}| j}|||fS )Nz)Only per tensor quantization is supported)r   ÚqschemeÚcalculate_qparamsÚfloatÚintÚdtype)r(   ÚscaleÚ
zero_pointrC   r   r   r   Úget_per_tensor_qparamso   s    rF   )r(   r   c                 C   sº   | j }d}|tjtjfv rxd}|  ¡ \}}t| jƒrTt| jƒ}||||dœ}tj	}q¤t
|ƒ}t|ƒ}|||dœ}tj}n,|tjkr”d}d}d|i}ntdt|ƒ ƒ‚|dus°J ‚|||fS )	z¸ Given an activation_post_process module,
    return node_type(e.g. call_function), quantize op(e.g. quantize_per_tensor) and a dictionary
    of extracted qparams from the module
    Nr!   )Ú_scale_Ú_zero_point_Z_axis_Ú_dtype_)rG   rH   rI   r#   ÚtorI   z,Unsupported dtype in get_quantize_node_info:)rC   ÚtorchZquint8Úqint8r@   r   r?   rB   Úch_axisZquantize_per_channelrA   Zquantize_per_tensorÚfloat16Ú	Exceptionr-   )r(   rC   Úquantize_opÚ	node_typerD   rE   rM   Úqparamsr   r   r   Úget_quantize_node_infow   s(    



rS   )Úin_nodeÚ
obs_moduleÚobs_nodeÚmodulesÚquantized_graphÚnode_name_to_scopeÚis_inputr   c                 C   s   |r\t |jƒ}|r|d nd}d}	|D ]&}
|
jdkr&|
jtjjjkr&|
}	 qNq&|	rV|	}d}n| }d}|r‚|j|v r‚||j \}}nd}|d }|}t	|ƒ\}}}| g}| 
¡ D ]<\}}|dv ràt|||| | |ƒ}| |¡ q®| |¡ q®| ||t|ƒi ¡S )a
   Add quantization nodes (eg. quantize_per_tensor/per_channel) for given node to graph
    with the qparams calculated from activation_post_process (obs_module).
    The observer node (obs_node) is used to find the FQN of the user of act_post_process.
    e.g. Given input `node` in `node = self.conv(x)`, insert node:
    `quantized_node = torch.quantize_per_tensor(x, self._scale_0, self._zer_point_0, self._dtype_0)`
    where self._scale_0, self._zero_point_0 and self._dtype_0 are
    calculated from `obs_module`
    r   Nr!   Ú_inputÚ_outputr   )rG   rH   )ÚlistÚusersr%   r   rK   ÚnnÚ
functionalÚlinearr$   rS   ÚitemsÚcreate_getattr_from_valuer3   Úcreate_nodeÚtuple)rT   rU   rV   rW   rX   rY   rZ   r^   Zfirst_linear_use_or_first_useZlinear_noder9   ÚprefixÚmodule_pathÚ_Úroot_moduleÚgraphrQ   rP   rR   ÚinputsÚkeyÚvalueZqparam_noder   r   r   Úquantize_node“   s4    
rn   c                 C   sD   t ƒ }|  |i ¡}dD ]$}| |i ¡}t | ¡ ƒ}||O }qt|ƒS )a_   Get all the unique custom module keys in the custom config dict
    e.g.
    Input:
    custom_config_dict = {
        "float_to_observed_custom_module_class": {
           "static": {
               CustomModule1: ObservedCustomModule
           },
           "dynamic": {
               CustomModule2: DynamicObservedCustomModule
           },
           "weight_only": {
               CustomModule3: WeightOnlyObservedCustomModule
           },
        },
    }

    Output:
    # extract all the keys in "static", "dynamic" and "weight_only" dict
    [CustomModule1, CustomModule2, CustomModule3]
    )ZstaticZdynamicZweight_only)ÚsetÚgetÚkeysr]   )Zcustom_config_dictZcustom_config_dict_keyZfloat_custom_module_classesZcustom_module_mappingZ
quant_modeZquant_mode_custom_module_configZ quant_mode_custom_module_classesr   r   r   Úget_custom_module_class_keysÍ   s    
rr   c                 C   s6   | t jkrt jjjS | t jkr(t jjjS td| ƒ‚d S )Nz&can't get linear prepack op for dtype:)rK   rN   ÚopsÚ	quantizedZlinear_prepack_fp16rL   Zlinear_prepackrO   )rC   r   r   r   Úget_linear_prepack_op_for_dtypeì   s
    



ru   )Úconv_opr   c                 C   sV   t jjjt jjjt jjjt jjjt jjj	t jjj
i}| | d ¡}|sRJ d | ¡ƒ‚|S )NzDidn't find prepack op for {})rK   r_   r`   Úconv1drs   rt   Zconv1d_prepackÚconv2dZconv2d_prepackÚconv3dZconv3d_prepackrp   r4   )rv   Zprepack_opsZ
prepack_opr   r   r   Úget_qconv_prepack_opô   s    ýrz   )rv   Úhas_relur   c                 C   s�   t jjjt jjjt jjjt jjjt jjj	t jjj
it jjjt jjjt jjjt jjjt jjj	t jjj	idœ}||  | ¡}|sŒJ d | |¡ƒ‚|S )N)TFz4Can't find corresponding quantized conv op for {} {})rK   r_   r`   rw   rs   rt   Zconv1d_relurx   Zconv2d_relury   Zconv3d_relurp   r4   )rv   r{   Zqconv_opZqconvr   r   r   Úget_qconv_opþ   s    ýýùr|   )rf   r   c                    s&   ˆ   dd¡‰ tjjdœ‡ fdd„}|S )Nr   rh   )Úmodulec                    s>   t dœ‡ fdd„}d}||ƒ}t| |ƒr:|d7 }||ƒ}q|S )N©Úic                    s   ˆ t | ƒ S ©N)r-   r~   ©rf   r   r   Úget_attr_name  s    zOget_new_attr_name_with_prefix.<locals>.get_new_attr_name.<locals>.get_attr_namer   r   )rB   Úhasattr)r}   r‚   r   Ú	attr_namer�   r   r   Úget_new_attr_name  s    

z8get_new_attr_name_with_prefix.<locals>.get_new_attr_name)r.   rK   r_   ÚModule)rf   r…   r   r�   r   Úget_new_attr_name_with_prefix  s    	r‡   )Únoder   c                 C   s„   | g}| g}|r€|  ¡ } t| jƒt| j ¡ ƒ }|D ]H}t|tƒsDq4|jdkrT dS | |¡ |jdkrr|j	t
ks4| |¡ q4q|S )a   Starting from a target node, trace back until we hit inpu or
    getattr node. This is used to extract the chain of operators
    starting from getattr to the target node, for example
    def forward(self, x):
      observed = self.observer(self.weight)
      return F.linear(x, observed)
    collect_producer_nodes(observed) will either return a list of nodes that
    produces the observed node or None if we can't extract a self contained
    graph without free variables(inputs of the forward function).
    r   Nr!   )Úpopr]   r&   r'   ÚvaluesÚ
isinstancer	   r%   r3   r   Úgetattr)rˆ   r,   ZfrontierÚall_argsÚargr   r   r   Úcollect_producer_nodes#  s    


r�   )ÚrootÚproducer_nodesr   c                    sl   t |ƒdksJ dƒ‚| ¡  tƒ }i ‰ ‡ fdd„}|D ]}| ||¡ˆ |< q6| ||d ƒ¡ t| |ƒ}|S )a-   Construct a graph module from extracted producer nodes
    from `collect_producer_nodes` function
    Args:
      root: the root module for the original graph
      producer_nodes: a list of nodes we use to construct the graph
    Return:
      A graph module constructed from the producer nodes
    r   z'list of producer nodes can not be emptyc                    s   t | ‡ fdd„ƒS )Nc                    s   ˆ |  S r€   r   ©rˆ   ©Úenvr   r   Ú<lambda>O  ó    zDgraph_module_from_producer_nodes.<locals>.load_arg.<locals>.<lambda>)r   )Úar“   r   r   Úload_argN  s    z2graph_module_from_producer_nodes.<locals>.load_argéÿÿÿÿ)r   Úreverser   Z	node_copyÚoutputr   )r�   r‘   rj   r˜   Zproducer_nodeZgraph_moduler   r“   r   Ú graph_module_from_producer_nodes>  s    

rœ   )r}   r   c                 C   s^   dd„ |   ¡ D ƒdd„ |  ¡ D ƒB }t|ƒdks>J d |¡ƒ‚t|ƒdkrVtt|ƒƒnd}|S )z†
    Returns the unique device for a module, or None if no device is found.
    Throws an error if multiple devices are detected.
    c                 S   s   h | ]
}|j ’qS r   ©Údevice©Ú.0Úpr   r   r   Ú	<setcomp>[  r–   z/assert_and_get_unique_device.<locals>.<setcomp>c                 S   s   h | ]
}|j ’qS r   r�   rŸ   r   r   r   r¢   \  r–   r   zMprepare only works with cpu or single-device CUDA modules, but got devices {}r   N)Ú
parametersÚbuffersr   r4   ÚnextÚiter)r}   Zdevicesrž   r   r   r   Úassert_and_get_unique_deviceV  s    ÿÿÿr§   )r}   rj   rf   rm   r   c                 C   s>   t |ƒ}|| ƒ}t| ƒ}|  |tj||d�¡ | d|¡}|S )z�
    Given a value of any type, creates a getattr node corresponding to the value and
    registers the value as a buffer to the module.
    r�   r    )r‡   r§   Zregister_bufferrK   Ztensorrd   )r}   rj   rf   rm   r…   r„   rž   Z	attr_noder   r   r   rc   d  s    rc   )Ú	node_namerD   rE   rW   rX   rY   r   c                 C   s@   |d }||  \}}t |||d |ƒ}	t |||d |ƒ}
|	|
fS )z–
    Create getattr nodes in the quantized graph for scale and zero point values.
    The nodes are registered with the root_module of the model.
    r   rG   rH   )rc   )r¨   rD   rE   rW   rX   rY   ri   rg   rh   Z
scale_nodeZzero_point_noder   r   r   Úcreate_qparam_nodesq  s
    r©   )rˆ   rW   Úcacher   c           	      C   sî  |r| |v r||  S d}t | tƒs*d}�n²| jdkr<d}�n | jdkrzt | jtƒsVJ ‚t|| j ƒrvt| jd ||ƒ}�nb| jdkrŒd}�nP| jdkr¸| jtj	u r¸t| jd ||ƒ}�n$| jdkrÊd}�n| jt
u rè| jd d	v rèd}nô| jd
k�r| jdk�rd}nÖd}| jD ]Ê}t |tƒ�rx|D ]P}t |tƒ�r$t|||ƒ}|�pJ| }|�r$| }|�rf||| < |    S �q$nZt |tƒ�r†nLt |tƒ�rÎt|||ƒ}|�p¨| }|�rÒ| }|�rÄ||| < |  S nd}| }�q|�rê||| < |S )zÒ
    If we know for sure that all of this node's args have no
    tensors (are primitives), return True.  If we either
    find a tensor or are not sure, return False. Note: this
    function is not exact.
    FTr   r"   r   r!   r    r   )ÚndimÚshaper#   Úsize)r‹   r	   r%   r   r-   r   Úall_node_args_have_no_tensorsr&   ÚoperatorÚgetitemrŒ   r]   rB   )	rˆ   rW   rª   r=   Zfound_one_tensorrŽ   Zlist_elZ!this_list_el_args_have_no_tensorsZthis_arg_args_have_no_tensorsr   r   r   r®   „  sj    






ÿÿÿ

r®   c                 C   s   | j dko| jdkS )zd
    Returns true if this node results in an integer, even if some of the args
    are Tensors.
    r#   r­   ©r%   r   r’   r   r   r   Únode_return_type_is_intÐ  s    r²   c                 C   s   | j dkr| jdkrdgS g S )z0
    Returns indexes of boolean Tensor args
    r#   Zmasked_fillr   r±   r’   r   r   r   Únode_bool_tensor_arg_indexes×  s    r³   c                 C   s&   | j dko | jtko | jd dk}|S )z“ Returns True if this node is a node that takes a Tensor as input and output some
    meta information about the Tensor, e.g. shape, size etc.
    r!   r   r¬   )r%   r   rŒ   r&   )rˆ   r=   r   r   r   Úis_get_tensor_info_nodeß  s     ÿr´   )rˆ   rW   Útarget_module_typeÚtarget_functional_typer   c                 C   sj   | j  ¡ D ]Z\}}|jdkr@|dur@t|t|jƒ |ƒr@|  S |jdkr
|dur
|j|kr
|  S q
dS )a%   Gets the next module that matches what is needed in
    is_target_module_type if it exists

    Args:
        node: The node whose users we want to look at
        target_module_type: Module type that we want to check
        target_functional_type: Functional type that we want to check
    r"   Nr!   )r^   rb   r%   r‹   r-   r   )rˆ   rW   rµ   r¶   Úuserrh   r   r   r   Úmaybe_get_next_moduleç  s    ÿÿ
r¸   )T)NN)>r*   rK   Ztorch.nnr_   Úutilsr   r   Ztorch.ao.quantization.quantizer   Ztorch.fxr   r   Ztorch.fx.graphr   r	   Útypingr
   r   r   r   r   r   r   r   r   r¯   r`   rw   rx   ry   ra   Z
layer_normZ
group_normZinstance_normZWEIGHT_INDEX_DICTZNON_QUANTIZABLE_WEIGHT_OPSZFUNCTIONAL_OPS_WITH_BIASr   r-   r>   rF   rS   r†   ÚtypeÚboolrn   rr   ru   rz   r|   r‡   r�   rœ   r§   rc   r©   r®   r²   rB   r³   r´   r¸   r   r   r   r   Ú<module>   s‚   ,ù
üB*ù:

ÿ
ù(L  üû