a
    Þñh‡  ã                   @   sD  d dl Z d dlmZmZ d dlmZ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 ddlmZ d	d
lmZmZmZ d	dlT d	dlmZmZ d dlmZ d dlZd dlZdd„ Z dd„ Z!dd„ Z"dd„ Z#dd„ Z$dd„ Z%dd„ Z&dd„ Z'e j(j)j*d	ge j(j)j+d	giZ,e j-j.j/j0e j-j.j/j1e j-j.j/j2hZ3G dd„ dƒZ4dS ) é    N)ÚGraphModuleÚProxy)ÚGraphÚNodeÚmap_arg)Úpropagate_qconfig_Úconverté   )Úget_qat_module_mappings)Úis_custom_module_classÚ get_observed_custom_module_classÚmark_observed_custom_moduleÚis_observed_custom_module)Ú_remove_qconfigé   )Úis_matchÚget_quant_patternsÚget_dynamic_quant_patterns)Ú*)Ú_parent_nameÚquantize_node)ÚOrderedDictc                    s   ‡ fdd„}|S )Nc                    s8   ‡ fdd„}d}||ƒ}t | |ƒr4|d7 }||ƒ}q|S )Nc                    s   ˆ t | ƒ S ©N)Ústr)Úi©Úprefix© ú^/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torch/quantization/fx/quantize.pyÚget_attr_name:   s    zOget_new_attr_name_with_prefix.<locals>.get_new_attr_name.<locals>.get_attr_namer   r   )Úhasattr)Úmoduler   r   Ú	attr_namer   r   r   Úget_new_attr_name9   s    

z8get_new_attr_name_with_prefix.<locals>.get_new_attr_namer   )r   r#   r   r   r   Úget_new_attr_name_with_prefix8   s    	r$   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).
    ÚplaceholderNÚcall_function)ÚpopÚlistÚargsÚkwargsÚvaluesÚ
isinstancer   ÚopÚappendÚtargetÚgetattr)ÚnodeÚnodesZfrontierÚall_argsÚargr   r   r   Úcollect_producer_nodesD   s    


r5   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   ©r1   ©Úenvr   r   Ú<lambda>o   ó    zDgraph_module_from_producer_nodes.<locals>.load_arg.<locals>.<lambda>©r   ©Úar7   r   r   Úload_argn   s    z2graph_module_from_producer_nodes.<locals>.load_argéÿÿÿÿ)ÚlenÚreverser   Ú	node_copyÚoutputr   )ÚrootZproducer_nodesÚgraphr>   Zproducer_nodeZgraph_moduler   r7   r   Ú graph_module_from_producer_nodes_   s    	
rF   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   rG   rI   r   r   r   rL   }   r:   r   zMprepare only works with cpu or single-device CUDA modules, but got devices {}r   N)Ú
parametersÚbuffersr@   ÚformatÚnextÚiter)r!   ZdevicesrH   r   r   r   Úassert_and_get_unique_devicew   s    ÿÿÿrR   c                 C   s   t | tjjƒpt | tjjƒS r   )r,   ÚtorchZquantizationZObserverBaseZFakeQuantize)r!   r   r   r   Úis_activation_post_process…   s    ÿrT   c                 C   s   t | ƒ\}}t|| ƒS r   )r   rT   )Únamer!   Únamed_modulesÚparent_nameÚ_r   r   r   Úis_submodule_of_fake_quant‰   s    rY   c                    s<   t ƒ ‰ dˆv rˆd ˆ d< ‡ ‡fdd„}|dƒ |dƒ ˆ S )a   flatten the global, object_type and module_name qconfig
    to the same qconfig_dict so that it can be used by
    propagate_qconfig_ function.
    "module_name_regex" is ignored for now since it's not supported
    in propagate_qconfig_, but it can be fixed later.

    For example:
    Input: {
      "": qconfig,
      "object_type": [
        (torch.add, qconfig)
      ],
      "module_name": [
        ("conv", qconfig)
      ]
    }

    Output: {
      "": qconfig,
      torch.add: qconfig,
      "conv": qconfig
    }
    Ú c                    s&   | ˆv r"ˆ|  D ]\}}|ˆ |< qd S r   r   )ÚkeyÚobjÚqconfig©Z	flattenedÚqconfig_dictr   r   Úflatten_key©   s    z/get_flattened_qconfig_dict.<locals>.flatten_keyÚobject_typeÚmodule_name)Údict)r_   r`   r   r^   r   Úget_flattened_qconfig_dict�   s    rd   c                 C   s*   dd„ }|d| ƒ |d| ƒ |d| ƒ dS )z2 Convert dict in qconfig_dict to ordered dict
    c                 S   s   t | | g ¡ƒ|| < d S r   )r   Úget)r[   r_   r   r   r   Ú_convert_to_ordered_dict¶   s    z>convert_dict_to_ordered_dict.<locals>._convert_to_ordered_dictra   Úmodule_name_regexrb   Nr   )r_   rf   r   r   r   Úconvert_dict_to_ordered_dict²   s    

rh   c                   @   s„   e Zd Zdd„ Zdd„ Zdd„ Zdd„ Zd	d
„ Zdd„ Zddd„Z	d dd„Z
dd„ Zd!dd„Zdd„ Zd"dd„Zdd„ Zdd„ ZdS )#Ú	Quantizerc                 C   s   d | _ d | _d | _d | _d S r   )Úactivation_post_process_mapÚqconfig_mapÚmodulesÚpatterns)Úselfr   r   r   Ú__init__Ë   s    zQuantizer.__init__c                 C   s   t |tƒ ddd� d S )NTF)ÚmappingÚinplaceZremove_qconfig)r   r
   )rn   rD   r   r   r   Ú_qat_swap_modulesç   s    zQuantizer._qat_swap_modulesc                    s  ˆ  dd ¡}|f‡fdd„	‰|f‡fdd„	}|f‡fdd„	‰|f‡ ‡fdd	„	‰ ‡ ‡‡‡fd
d„}tƒ ˆ_|jD ]¨}|jdkrœt|jƒ\}}	||ƒˆj|j< qn|jdkr¾||jƒ}
|
ˆj|j< qn|jdkrè|jd }ˆj|j ˆj|j< qn|jdkrn||jƒ}|ˆj	|j _
|ˆj|j< qnd S )NrZ   c                    s   ˆ d   | |¡S ©Nra   ©re   )Úmodule_typeÚfallback_qconfig©r_   r   r   Úget_module_type_qconfigð   s    z@Quantizer._generate_qconfig_map.<locals>.get_module_type_qconfigc                    s   ˆ d   | |¡S rs   rt   )Úfunctionrv   rw   r   r   Úget_function_qconfigô   s    z=Quantizer._generate_qconfig_map.<locals>.get_function_qconfigc                    s.   ˆ d   ¡ D ]\}}t || ¡r|  S q|S )Nrg   )ÚitemsÚreÚmatch)rb   rv   Zregex_patternr]   rw   r   r   Úget_module_name_regex_qconfigø   s    
zFQuantizer._generate_qconfig_map.<locals>.get_module_name_regex_qconfigc                    s>   | dkr|S | ˆd v r$ˆd |  S t | ƒ\}}ˆ ||ƒS d S )NrZ   rb   )r   )rb   rv   ÚparentrX   )Úget_module_name_qconfigr_   r   r   r€      s    z@Quantizer._generate_qconfig_map.<locals>.get_module_name_qconfigc                    s*   ˆt ˆj|  ƒƒ}ˆ| |ƒ}ˆ | |ƒ}|S r   )Útyperl   )rb   Zmodule_type_qconfigZmodule_name_regex_qconfigZmodule_name_qconfig)r€   r~   rx   rn   r   r   Úget_qconfig  s    ÿÿÿz4Quantizer._generate_qconfig_map.<locals>.get_qconfigÚget_attrr&   Úcall_methodr   Úcall_module)re   rc   rk   r2   r-   r   r/   rU   r)   rl   r]   )rn   rD   Zinput_graphr_   Zglobal_qconfigrz   r‚   r1   rb   rX   Zfunction_qconfigZself_objZmodule_qconfigr   )r€   r~   rx   r_   rn   r   Ú_generate_qconfig_mapê   s2    ÿÿÿ	ÿ	







zQuantizer._generate_qconfig_mapc                    sp  |st  ˆ¡‰|ˆ_ˆjr$tƒ ˆ_ntƒ ˆ_t|ƒ}tˆ|ƒ ˆjrNˆ 	ˆ¡ t
ˆ ¡ ƒˆ_t|ƒ ˆ ˆˆj|¡ ˆ ˆjˆjˆj¡}ˆ ˆj|¡}t
ƒ ˆ_i ‰ tƒ ‰tƒ ‰‡ fdd„‰ˆjjD �]€}|jˆv rÔqÂ|jd ‰| |jd¡\}	}
}}|	d u �rˆ |ˆ¡ˆ |j< �n~|	|u �r€ˆ |ˆ¡ˆ |j< |d u �r<qÂ‡ ‡‡‡‡‡‡fdd„}t|tƒ�r°ˆj|j }tt|ƒƒ}| |¡}t|t|ƒƒ t |jƒ\}}t!ˆj| ||ƒ ˆj�rºqÂt|t"ƒ�r|j#dv �säJ d|j# d	 ƒ‚‡‡fd
d„‰ˆ|j$d ƒ�r~ˆ %|j¡ nnt|t&ƒ�s(t|t'ƒ�rP|j(�sP|j$d jˆv �r~ˆ %|j¡ n.|d u�r’|j(�r’| )¡ }t*ˆƒ}||||ƒ nˆ |ˆ¡ˆ |j< |jˆvrÂ|j|v rÂt+ˆƒ}|ˆƒ}||j \}
}}|d urÂ|�rÜ| ,¡ n| )¡ }t*ˆƒ}|�rü| -|¡ |ˆj|j< t!ˆ|ˆj|j ƒ ˆ .d|ˆ|ƒfi ¡ˆ |j< ˆ %|j¡ qÂˆ /ˆˆjj0ƒ¡ t1ˆˆƒ‰ˆ 2ˆ¡ ˆS )Nc                    s   t | ‡ fdd„ƒS )Nc                    s
   ˆ | j  S r   ©rU   r6   r7   r   r   r9   Q  r:   z6Quantizer._prepare.<locals>.load_arg.<locals>.<lambda>r;   r<   r7   r   r   r>   P  s    z$Quantizer._prepare.<locals>.load_argZ_activation_post_process_©NNNNc                    sh   t ˆƒ}|ˆƒ}tˆ||ƒ |ˆj| j< ˆ d|ˆ| ƒfi ¡ˆ | j< ˆ | j¡ |rdtˆ|ƒ |¡ d S )Nr…   )r$   Úsetattrrj   rU   Úcreate_nodeÚaddr0   Úto)r1   ZobserverrH   Úget_new_observer_nameÚobserver_name)r8   r>   ÚmodelÚobserved_graphÚobserved_node_names_setr   rn   r   r   Úinsert_observer`  s    z+Quantizer._prepare.<locals>.insert_observer©r…   r&   r„   úCopyNode of type ú is not handledc                    s0   t | tƒr| jˆv S t | tƒr,ttˆ | ƒƒS d S r   )r,   r   rU   r(   ÚallÚmap)Z	input_arg)Úis_observedr‘   r   r   r˜   �  s    


z'Quantizer._prepare.<locals>.is_observedr   r…   )3ÚcopyÚdeepcopyÚis_dynamic_quantr   rm   r   rd   r   Ztrainingrr   rc   rV   rl   rh   r†   rE   Ú_find_matchesÚ_find_quantsrj   r   Úsetr2   rU   re   rB   r,   ÚCustomModuleQuantizeHandlerr/   r   r�   Ú
from_floatr   r   r‰   ÚCopyNoder-   r)   r‹   ÚAddZMulZ	all_nodesZ
activationrR   r$   ZweightrŒ   rŠ   rC   Úresultr   Ú
save_state)rn   r�   r_   rq   r›   Zflattened_qconfig_dictÚmatchesÚquantsr1   Ú	root_noderX   r\   r]   r’   Zcustom_moduleZobserved_custom_module_classZobserved_custom_modulerW   rU   Znew_observerrH   r�   rŽ   Ú	is_weightr   )r8   r˜   r>   r�   r�   r‘   r   rn   r   Ú_prepare-  s˜    










ÿÿü ÿ


zQuantizer._preparec                 C   s   | j |_| j|_| j|_d S r   )rj   Ú_activation_post_process_maprm   Ú	_patternsrk   Ú_qconfig_map)rn   Úobservedr   r   r   r¤   ª  s    zQuantizer.save_statec                 C   sb   d}t |dƒsJ d| ƒ‚t |dƒs0J d| ƒ‚t |dƒsFJ d| ƒ‚|j| _|j| _|j| _d S )Nz1please make sure the model is produced by preparerª   z1did not found _activation_post_process attribute r«   z"did not found _patterns attribute r¬   z%did not found _qconfig_map attribute )r    rª   rj   r«   rm   r¬   rk   )rn   r­   Úerr_msgr   r   r   Úrestore_state¯  s    ÿÿÿzQuantizer.restore_stateFc                 C   s   | j |||dd�S )NF©r›   ©r©   ©rn   r�   r_   rq   r   r   r   Úprepare»  s    zQuantizer.preparec                 C   s   | j |||dd�S )NTr°   r±   r²   r   r   r   Úprepare_dynamic¾  s    zQuantizer.prepare_dynamicc                 C   sh   |j jD ]Z}|jdkr|jtv rt|jƒD ]6\}}|t|j v r*t|ƒ}|dur*t||ƒ}|ƒ  q*qdS )z÷ Extract the subgraph that produces the weight for dynamically quantized
        node and run the subgraph to observe the weight.
        Note that the observers of dynamically quantized modules are run during
        the conversion step.
        r&   N)	rE   r2   r-   r/   ÚWEIGHT_INDEX_DICTÚ	enumerater)   r5   rF   )rn   r­   r1   r   Únode_argZweight_observer_nodesZweight_observer_moduler   r   r   Ú_run_weight_observersÁ  s    ÿ
zQuantizer._run_weight_observersc                    sZ  ˆ  |¡ |st |¡}|ˆ_ˆjr.ˆ |¡ | ¡  ¡  t| ¡ ƒˆ_	ˆ 
|jˆj	ˆj¡}ˆ |j|¡‰tƒ ˆ_i ‰ i ‰‡ ‡fdd„‰‡ ‡‡‡fdd„‰‡ ‡fdd„‰‡‡‡fdd„}‡ ‡‡fd	d
„‰|jjD �]|}| |jd¡\}}	}
}||u �rŒ|d u �rˆj |ˆ¡}d}nX|
 ˆ||¡}t|
tƒ�r\|jdv �sLJ d|j d ƒ‚ˆ|jd ƒ}nd}ˆj�rld}|�r~|ˆ|j< qÐ|ˆ |j< qÐn|d u�r˜qÐ|jdk�r:tˆj	|j ƒ�r:ˆj	|j }|jd }|jtjk�rðˆj |ˆ¡ˆ |j< qÐ|jˆv �rˆ|j ˆ|j< qÐˆj	d }t|ˆjˆ|jd ƒ|ƒˆ|j< qÐˆj |ˆ¡ˆ |j< qÐˆj t |jj!ˆƒ¡ tƒ }i ‰ ‡ fdd„}ˆjjD ]N}|jdk�r¾tˆj	|j ƒ�r¾ˆ |jd j ˆ |j< n| ||¡ˆ |j< �q„| t ˆjj!|ƒ¡ t| ¡ ƒ}g }| ¡ D ],\}}t|ƒ�r t"|||ƒ�s | #|¡ �q |D ]}t$||ƒ �q2t%|ƒ t&||ƒ}|S )Nc                    s^   | j ˆ vrT| j ˆv s:J d| j  d tˆ ƒ d tˆƒ ƒ‚tˆ| j  ƒ ¡ jˆ | j < ˆ | j  S )Nz0trying to load float node but did not find node:z1 in quantized or non quantized environment, env: z quant_env:)rU   r   r   Z
dequantizer1   ©Ún©r8   Ú	quant_envr   r   Úload_non_quantizedé  s    
ÿÿþþÿz.Quantizer._convert.<locals>.load_non_quantizedc                    sv   | j ˆvrl| j ˆ v s.J d| j  d tˆ ƒ ƒ‚| j ˆv sFJ d| j  ƒ‚ˆ| j  d }| ˆˆ | j  ¡ˆ| j < ˆ| j  S )Nz4trying to load quantized node but did not find node:z in float environment:z#did not find quant object for node:r   )rU   r   r   )rº   Zquant)r8   r¼   r¦   rn   r   r   Úload_quantizedò  s    
ÿÿÿz*Quantizer._convert.<locals>.load_quantizedc                    sH   | j ˆ v s&| j ˆv s&J d| j  d ƒ‚| j ˆv r:ˆ| j  S ˆ | j  S d S )Nznode z% does not exist in either environmentr‡   r¹   r»   r   r   Úload_xü  s    ÿ

z"Quantizer._convert.<locals>.load_xc                    s:   ˆ du s$t ˆ tttfƒs$J tˆ ƒƒ‚‡‡‡‡ fdd„}|S )a-  
            Input: quantized, which can be None, list, boolean or tuple
              - if quantized is a list or tuple, then arg should be a list and the args with corresponding
                indexes will be quantized
              - if quantized is a boolean, then all args will be quantized/not quantized
              - if quantized is None, then we'll load the node as long as it exists

            Output: fn which takes arg_or_args, and loads them from the corresponding
              environment depending on the value of quantized.
            Nc                    s¢   ˆd u rt | ˆƒS tˆtƒr.t | ˆr(ˆnˆ ƒS tˆttfƒržt| ttfƒsRJ | ƒ‚g }t| ƒD ]2\}}|ˆv r€| t |ˆƒ¡ q^| t |ˆ ƒ¡ q^t| ƒ|ƒS d S r   )r   r,   ÚboolÚtupler(   r¶   r.   r�   )Zarg_or_argsZloaded_argsr   r=   )r½   r¾   r¿   Ú	quantizedr   r   Úload_arg_impl  s    

z;Quantizer._convert.<locals>.load_arg.<locals>.load_arg_impl)r,   rÁ   r(   rÀ   r�   )rÂ   rÃ   )r½   r¾   r¿   )rÂ   r   r>     s    $z$Quantizer._convert.<locals>.load_argc                    s|   t | tƒrD| jˆ v s&| jˆv s&J dƒ‚| jˆv r4dS | jˆ v rxdS n4t | tƒrxtˆ| ƒ}t|ƒrddS t|ƒspdS tdƒ‚d S )Nz'Expecting node to be in the environmentTFz2partially quantized inputs in list not handled yet)r,   r   rU   r(   r—   r–   ÚanyÚ	Exception)r1   rÂ   )r8   Úis_quantizedr¼   r   r   rÆ   "  s    




z(Quantizer._convert.<locals>.is_quantizedrˆ   Fr“   r”   r•   r   Tr…   rZ   c                    s   t | ‡ fdd„ƒS )Nc                    s
   ˆ | j  S r   r‡   r6   r7   r   r   r9   t  r:   z6Quantizer._convert.<locals>.load_arg.<locals>.<lambda>r;   r<   r7   r   r   r>   s  s    )'r¯   r™   rš   r›   r¸   ÚevalÚcpurc   rV   rl   rœ   rE   rm   r�   r   Úquantized_graphr2   re   rU   rB   r   r,   r¡   r-   r)   rT   r/   ZdtyperS   Úfloat16r   rC   r   r£   rY   r.   Údelattrr   r   )rn   r�   rq   Údebugr›   r¥   r>   r1   r§   Úmatchedr\   r]   r£   rÂ   Zobserver_moduleZ	prev_nodeZroot_moduleZact_post_process_removed_graphÚmodule_dictZto_be_removedrU   r!   rº   r   )r8   rÆ   r½   r¾   r¿   r¼   r¦   rn   r   Ú_convertÔ  sš    


	


ü



þ
ÿ
zQuantizer._convertc                    s(  t ƒ }t ƒ }|jjD ]V}|jdkr|jtv rt|ƒ}|d ur|D ]}|||j< q@t||ƒ}|ƒ }|||j< qt	ƒ }	i ‰ ‡ fdd„}
t
dƒ}|}|j}|jD ]n}| |jd ¡}||u rê||j }||ƒ}t|||ƒ |	 d|di ¡ˆ |j< qš|d uröqšqš|	 ||
¡ˆ |j< qš|	 |
|jƒ¡ t||	ƒ}|S )Nr&   c                    s   t | ‡ fdd„ƒS )Nc                    s
   ˆ | j  S r   r‡   r6   r7   r   r   r9   ¢  r:   z:Quantizer._fold_weight.<locals>.load_arg.<locals>.<lambda>r;   r<   r7   r   r   r>   ¡  s    z(Quantizer._fold_weight.<locals>.load_argZ_fx_pass_packed_weight_rƒ   r   )rc   rE   r2   r-   r/   ÚWEIGHT_PREPACK_OPSr5   rU   rF   r   r$   re   r‰   rŠ   rB   rC   r£   r   )rn   rÂ   Zpacked_weightsZfolded_nodesr1   Znodes_to_foldZnode_to_foldZprepacking_moduleZpacked_weightZfolded_graphr>   Zget_new_packed_weight_nameZquantized_rootrÉ   Zprepack_nodeZpacked_weight_namer   r7   r   Ú_fold_weightŒ  sD    ÿ

ÿ
zQuantizer._fold_weightc                 C   s"   |   ||||¡}|s|  |¡}|S r   )rÏ   rÑ   )rn   r�   rq   rÌ   Z
is_dynamicrÂ   r   r   r   r   º  s    
zQuantizer.convertc                    s  i }t ƒ }‡ fdd„‰ t|jƒD ]€}|j|vr |j|vr | ¡ D ]^\}}t|||ƒr@g }	ˆ |||	ƒ |	D ]0}
||	|| |ƒ| j|
j f||
j< | |
j¡ qh q q@q |jD ]X}|jdkr¨t	t
| j|j ƒƒsÚt| j|j ƒr¨| j|j }||gt| |ƒ|f||j< q¨|S )aÄ  
        Matches the nodes in the input graph to quantization patterns, and
        outputs the information needed to quantize them in future steps.

        Inputs:
          - graph: an fx.Graph object
          - modules: a mapping of fully qualified module name to instance,
              for example, {'foo': ModuleFoo, ...}
          - patterns: a mapping from a tuple of nodes in reverse order to
              uninitialized QuantizeHandler subclass.

        Outputs a map of
          node_name ->
            (node, matched_values, QuantizeHandler instance, qconfig)

        For example, {
          'relu_1': (relu_1, [relu_1], <CopyNode instance>, QConfig(...)),
          ...
        }
        c                    s\   t | tƒrN| ^}}ˆ |||ƒ | d turXt||jƒD ]\}}ˆ |||ƒ q6n
| |¡ d S )Nr   )r,   rÁ   r0   Úzipr)   r.   )Úpatternr1   rÍ   Úsr)   Ú
subpatternr4   ©Úrecord_matchr   r   r×   Ø  s    
z-Quantizer._find_matches.<locals>.record_matchr…   )rž   Úreversedr2   rU   r{   r   rk   r‹   r-   r   r�   rl   r/   r   rŸ   )rn   rE   rl   rm   Z	match_mapZall_matchedr1   rÓ   ÚvaluerÍ   rº   Zcustom_module_qconfigr   rÖ   r   rœ   À  s.    
 

ÿþÿzQuantizer._find_matchesc           	         sœ   i ‰ ‡ ‡fdd„}|j D ]~}|j|v r||j \}}}}t|tƒrFd}||u rt|d j||d |ƒƒ t|d j||d |ƒƒ t|d |d|ƒƒ qˆ S )a{  
        Takes the nodes in the input graph and pending matches, and finds and
        returns the input and output nodes which need to be quantized.

        Inputs:
          - graph: an fx.Graph object
          - matches: output of self._find_matches function

        Outputs a map of
          node_name -> (QuantizeHandler instance (always DefaultQuant), qconfig)
        c                    s   ‡ ‡‡‡fdd„}|S )Nc                    st   d}t ˆ tƒrPˆ jdkrPˆ jtv rPtˆ jƒD ]"\}}| |u r,|tˆ j v r,d}q,ˆjrZ|rptˆ| ƒˆ|fˆ| j	< d S )NFr&   T)
r,   r   r-   r/   rµ   r¶   r)   r›   ZDefaultQuantrU   )r4   r¨   r   r·   )r1   r]   r¦   rn   r   r   Ú	visit_arg  s    
z8Quantizer._find_quants.<locals>.visit.<locals>.visit_argr   )r1   r]   rÚ   ©r¦   rn   )r1   r]   r   Úvisit  s    z%Quantizer._find_quants.<locals>.visitNr?   r   )r2   rU   r,   r¡   r   r)   r*   )	rn   rE   r¥   rÜ   r1   r§   rÍ   r\   r]   r   rÛ   r   r�   ù  s    


zQuantizer._find_quantsN)F)F)FFF)FFF)Ú__name__Ú
__module__Ú__qualname__ro   rr   r†   r©   r¤   r¯   r³   r´   r¸   rÏ   rÑ   r   rœ   r�   r   r   r   r   ri   Ê   s   C}


 9.
9ri   )5rS   Z	torch._fxr   r   Ztorch._fx.graphr   r   r   Ztorch.quantizationr   r   Zquantization_mappingsr
   Zcustom_module_class_mappingsr   r   r   r   Úquantizer   Zpattern_utilsr   r   r   Zquantization_patternsÚutilsr   r   Úcollectionsr   r™   r|   r$   r5   rF   rR   rT   rY   rd   rh   ÚnnZ
functionalZconv2dZlinearrµ   Z_opsÚopsrÂ   Zlinear_prepackZlinear_prepack_fp16Zconv2d_prepackrÐ   ri   r   r   r   r   Ú<module>   s8   %þ


ý