a
    Ž¥»a¡_  ã                   @   sØ  d dl mZmZmZmZmZmZmZ d dlm	Z	 d dl
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 d	d
lmZ ddl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%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ d dl,m-Z-m.Z. d	dl#m/Z/m0Z0 ddl1m1Z1 e
j2j3j4j5e
j2j3j4j6e
j2j3j4j7e
j2j3j4j8e
j2j3j4j9hZ:eddœdd„Z;eee<ee<e=f f edœdd„Z>eeeeef ee<ee<e=f f ee<ef f dœdd„Z?d ee@ee<ef e@e@edœdd„ZAdS )!é    )ÚAnyÚDictÚTupleÚListÚCallableÚOptionalÚUnion)ÚdefaultdictN)ÚGraphModuleÚProxyÚmap_arg)ÚGraphÚNode)ÚArgumenté   )ÚPatterné   )Ú
QConfigAny)Úfind_matches)Úis_observed_moduleÚis_observed_standalone_moduleÚQuantizedGraphModule)ÚQuantizeHandler)Úupdate_obs_for_equalizationÚconvert_eq_obs)Úis_get_tensor_info_nodeÚnode_return_type_is_intÚquantize_nodeÚget_new_attr_name_with_prefixÚcollect_producer_nodesÚ graph_module_from_producer_nodesÚget_custom_module_class_keysÚWEIGHT_INDEX_DICT)Ú_remove_qconfigÚis_activation_post_process)Ú"activation_is_statically_quantizedÚactivation_dtype)Úlower_to_fbgemm)ÚobservedÚreturnc                 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 dynamic quant
    or weight only quant node and run the subgraph to observe the weight.
    Note that the observers of dynamic quant or weight only quant ops are
    run during the convert step.
    Úcall_functionN)	ÚgraphÚnodesÚopÚtargetr"   Ú	enumerateÚargsr   r    )r(   ÚnodeÚiÚnode_argZweight_observer_nodesZweight_observer_module© r4   úW/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/torch/quantization/fx/convert.pyÚrun_weight_observers;   s    ÿÿr6   )Ú	quantizedÚnode_name_to_scoper)   c                    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„}
| }| j}|jD ]š}| 
|jd¡}||u �r||j }t|jƒd }||j \}}t|d ƒ}||ƒ}t|||ƒ |	 d|di ¡ˆ |j< q’|du�rq’q’|	 ||
¡ˆ |j< q’t||	|jƒ} | S )	zå
    Trace back from the weight node util we hit getattr, reconstruct the
    graph module with the traced nodes and run the graph module to pack the
    weight. then replace the original chain of ops with the packed weight.
    r*   Nc                    s   t | ‡ fdd„ƒS )Nc                    s
   ˆ | j  S ©N©Úname©r1   ©Úenvr4   r5   Ú<lambda>k   ó    z/fold_weight.<locals>.load_arg.<locals>.<lambda>©r   ©Úar=   r4   r5   Úload_argj   s    zfold_weight.<locals>.load_argr   Z_packed_weight_Zget_attrr4   )Údictr+   r,   r-   r.   ÚWEIGHT_PREPACK_OPSr   r;   r    r   ÚgetÚlistZusersr   ÚsetattrZcreate_nodeÚ	node_copyr   Zpreserved_attr_names)r7   r8   Zpacked_weightsZfolded_nodesr1   Znodes_to_foldZnode_to_foldZprepacking_moduleZpacked_weightZfolded_graphrD   Zquantized_rootÚquantized_graphZprepack_nodeZop_nodeÚmodule_pathÚ_Zget_new_packed_weight_nameZpacked_weight_namer4   r=   r5   Úfold_weightN   sH    ÿ



ÿÿ
rN   c                 C   s,   t | ƒsJ dƒ‚| j}| j}| j}|||fS )Nz-incoming model must be produced by prepare_fx)r   Z_prepare_custom_config_dictZ_node_name_to_scopeZ	_patterns)r(   Úprepare_custom_config_dictr8   Úpatternsr4   r4   r5   Úrestore_state†   s    
ÿÿrQ   FT)ÚmodelÚis_referenceÚconvert_custom_config_dictÚis_standalone_moduleÚ_remove_qconfig_flagr)   c           $         s  |du ri }t | ƒ\}‰}| j}|s,|  ¡  t| jdd�ƒ}t|dƒ}	t| j||||	d�}
| jdurzt	| |ƒ}t
| ||ƒ t| ƒ tƒ ‰tdd„ ƒ‰ g }| jjD ]}|jdkr | |j¡ q ttd	œ‡ fd
d„‰tjdœ‡ ‡fdd„‰ttd	œ‡ fdd„‰tttt tttjf tjttdf f  ttgtf dœ‡‡‡fdd„}ttdœ‡ ‡fdd„‰d+ttt tt!tj"j#f tdœ‡fdd„}ttt!tj"j#f ddœ‡ ‡‡‡fdd„}d}d}| $dg ¡}| $d g ¡}| jjD �]N}|jd!k�r*|}|d"7 }||v �rt%|j&d ˆƒ}nt%|j&d ˆƒ}ˆ '|¡ �qÒ|
 $|jd#¡\}}}}}||u �r4|jd$k�odt(||j) ƒ}|du �rˆ|�sˆˆ *|ˆ¡}d}n||du�s–J ‚|�rÊ||j) j+ ,¡ }t-|ƒd"k�sÂJ d%ƒ‚d|v }||j }|j.|||ˆˆ|||d&�}|�s||||||ƒ}|�r|ˆ |j t/|ƒ< n|ˆ |j tj0< �qÒn4|du�rh|du �rÒˆ *|ˆ¡}|ˆ |j tj0< �qÒ|jd$k�r�t1||j) ƒ�r�|||ƒ n�|jdk�ræ|} |d"7 }| |v �rÌˆ *|ˆ¡ˆ |j tj2< nˆ *|ˆ¡ˆ |j tj0< n:t3|ƒ�rˆ *|ˆ¡ˆ |j d< nˆ *|ˆ¡ˆ |j tj0< �qÒtƒ }!i ‰ttd'œ‡fd(d)„}"ˆjD ]r}|jd!k�rr|! 't%|j&d |"ƒ¡ �qH|jd$k�r¦t1||j) ƒ�r¦ˆ|j&d j ˆ|j< n|! *||"¡ˆ|j< �qH|�rÊt4| ƒ t5| $d*g ¡ƒ}#t6| |!|#ƒ} |�sþt7| ˆƒ} t8| ƒ} | S ),ag   standalone_module means it a submodule that is not inlined in
    parent module, and will be quantized separately as one unit.

    Returns a quantized standalone module, whether input/output is quantized is
    specified by prepare_custom_config_dict, with
    input_quantized_idxs, output_quantized_idxs, please
    see docs for prepare_fx for details
    NF)Zremove_duplicateZ)observed_to_quantized_custom_module_class)Úcustom_module_classesc                   S   s   t tƒS r9   )r	   r   r4   r4   r4   r5   r?   É   r@   zconvert.<locals>.<lambda>Úplaceholder)Únr)   c                    sÄ   | j ˆ v s$J d| j  d tˆ ƒ ƒ‚ˆ | j  }tj|v rB|tj S d |v rR|d  S d }tjtjtjfD ]}||v rf|| } q€qf|d us–J d |¡ƒ‚t|ƒ 	¡ j
ˆ | j  tj< ˆ | j  tj S d S )Nz0trying to load float node but did not find node:z	 in env: z+Did not find a supported quantized dtype:{})r;   ÚstrÚtorchÚfloatÚquint8Úqint8Úfloat16Úformatr   Z
dequantizer1   )rY   Údtype_to_nodeZquantized_nodeÚdtyper=   r4   r5   Úload_non_quantizedÐ   s,    ÿþýÿ


z#convert.<locals>.load_non_quantized©rb   c                    s   t dœ‡ ‡‡fdd„}|S )N)rY   c                    s‚   | j ˆv s$J d| j  d tˆƒ ƒ‚ˆ| j  }ˆ }|tjkrH||vrHd }|tjd fv r^ˆ| ƒS ||v szJ dˆ › d|› �ƒ‚|| S )Nz4trying to load quantized node but did not find node:z in environment:z
Expecting z in )r;   rZ   r[   r\   )rY   ra   Zlocal_dtype)rb   r>   rc   r4   r5   Úload_quantized_implæ   s"    ÿÿÿÿ
z<convert.<locals>.load_quantized.<locals>.load_quantized_impl)r   )rb   re   )r>   rc   rd   r5   Úload_quantizedå   s    zconvert.<locals>.load_quantizedc                    sz   | j ˆ v sJ d| j  d ƒ‚ˆ | j  }tjtjtjtjd g}|D ]}||v r@||   S q@td|› d|› d| j › �ƒ‚d S )Nznode z does not exist in environmentzdtype z not found in environment: z
 for node )r;   r[   r]   r^   r_   Úfloat32Ú	Exception)rY   ra   Zdtypesrb   r=   r4   r5   Úload_xõ   s    ÿ
zconvert.<locals>.load_x.)r7   r)   c                    s`   ˆ du s(t ˆ ttttjfƒs(J tˆ ƒƒ‚t ˆ tttfƒrJtˆ ƒdkrJtj‰ ‡‡‡‡ fdd„}|S )a­  
        Input: quantized, which can be None, torch.dtype, list or tuple
          - if quantized is None, then we'll load the node as long as it
            exists
          - if quantized is a dtype, then all args will be
            quantized to the specific dtype
          - if quantized is an empty list or tuple, then it is the same as load_arg(quantized=torch.float)
          - if quantized is a list or tuple, then arg should be a list and
            the args with corresponding indexes will be quantized to torch.quint8


        Output: fn which takes arg_or_args, and loads them from the
            corresponding environment depending on the value of quantized.
        Nr   c                    s>  ˆ}t ˆttfƒr6tˆƒdkr6t | tƒr6dˆv r6tj}|d u rHt| ˆƒS t |tjƒrbt| ˆ|ƒƒS t |ttfƒrØt | ttfƒs†J | ƒ‚g }t	| ƒD ]8\}}||v rº| 
t|ˆtjƒƒ¡ q’| 
t|ˆ ƒ¡ q’t| ƒ|ƒS t |tƒ�r:g }t	| ƒD ]<\}}||v �r| 
t|ˆ|| ƒƒ¡ qð| 
t|ˆ ƒ¡ qðt| ƒ|ƒS d S )Nr   r   )Ú
isinstanceÚtuplerH   Úlenr   r[   r]   r   rb   r/   ÚappendÚtyperE   )Zarg_or_argsZupdated_quantizedZloaded_argsr2   rC   )rc   rf   ri   r7   r4   r5   Úload_arg_impl  s<    
ÿÿ
þ
z0convert.<locals>.load_arg.<locals>.load_arg_impl)	rj   rk   rH   rE   r[   rb   rn   rl   r\   )r7   ro   )rc   rf   ri   )r7   r5   rD   ÿ   s    ÿÿ'zconvert.<locals>.load_arg)r3   r)   c                    s–   t | tƒrX| jˆv sJ dƒ‚| jˆv rRˆ| j ‰ t‡ fdd„tjtjtjfD ƒƒS dS n:t | tƒrŽt	ˆ| ƒ}t
|ƒrxdS t|ƒs„dS tdƒ‚ndS d S )Nz+Expecting node_arg to be in the environmentc                    s   g | ]}|ˆ v ‘qS r4   r4   )Ú.0Úx©ra   r4   r5   Ú
<listcomp>E  r@   z:convert.<locals>.node_arg_is_quantized.<locals>.<listcomp>FTz2partially quantized inputs in list not handled yet)rj   r   r;   Úanyr[   r]   r^   r_   rH   ÚmapÚallrh   )r3   r7   )r>   Únode_arg_is_quantizedrr   r5   rw   ?  s$    
ÿ

"

ÿz&convert.<locals>.node_arg_is_quantized)r1   ÚobjÚqconfigÚmodulesr)   c                    sp   |dusJ ‚|  ||¡}| |¡rL| jdv s>J d| j d ƒ‚ˆ | jd ƒ}t|ƒr\| ¡ s`d}t| ƒrld}|S )z* Check if output node is quantized or not N)Úcall_moduler*   Zcall_methodz$FixedQParamsQuantizeHandler of type z is not handledr   F)Úis_output_quantizedZ8should_mark_output_quantized_from_input_quantized_statusr-   r0   r%   Zinput_output_observedr   )r1   rx   ry   rz   rS   r7   )rw   r4   r5   r|   T  s    
üÿz$convert.<locals>.is_output_quantized)r1   rz   r)   c           	   	      s(  |dusJ ‚t | jtƒsJ ‚|| j }| jd }|jtjkrVˆ | ˆ¡ˆ | j tj	< nÎt |t
ƒrØ|jˆ v rØˆ |j }|j}||v r–|| ˆ | j |< n@|d }t |t
ƒs¬J ‚|j}tˆ|ƒ|| |ˆˆdd�ˆ | j |< nL|d }t | jd t
ƒsôJ ‚|j}tˆ| jd ƒ|| |ˆˆdd�ˆ | j |< dS )zQ Given a activation_post_process module call node, insert a
        quantize nodeNr   Ú T)Zis_input)rj   r.   rZ   r0   rb   r[   rg   rJ   r;   r\   r   r   )	r1   rz   Zobserver_moduleZ	prev_nodeZprev_dtype_to_nodeZcurrent_dtypeZroot_moduleZobserver_dtyperb   )r>   rc   r8   rK   r4   r5   Úinsert_quantize_nodex  s@    

ÿ
ýÿüÿz%convert.<locals>.insert_quantize_noder   Úinput_quantized_idxsÚoutput_quantized_idxsÚoutputr   )NNNNNr{   z,Currently standalone only support one output)rS   rT   )rC   r)   c                    s   t | ‡ fdd„ƒS )Nc                    s
   ˆ | j  S r9   r:   r<   ©Ú
remove_envr4   r5   r?     r@   z2convert.<locals>.load_arg_remove.<locals>.<lambda>rA   rB   r‚   r4   r5   Úload_arg_remove  s    z convert.<locals>.load_arg_removeÚpreserved_attributes)F)9rQ   Z_qconfig_mapÚcpurE   Znamed_modulesr!   r   r+   Z_equalization_qconfig_mapr   r   r6   r   r	   r,   r-   rm   r;   r   r[   rb   r   r   r   Úintr   r   r   r   r   Úboolr   r   rZ   ÚnnÚModulerG   r   r0   r�   r   r.   rJ   Z(_standalone_module_output_quantized_idxsÚtolistrl   Úconvertr&   r\   r$   r]   r   r#   Úsetr   rN   r'   )$rR   rS   rT   rU   rV   rP   rO   Zqconfig_maprz   rW   ÚmatchesZweight_eq_obs_dictZgraph_inputsr1   rD   r|   r~   Zplaceholder_node_seen_cntZoutput_node_seen_cntr   r€   Zcur_output_node_idxZgraph_outputZ	root_nodeÚmatchedZmatched_patternrx   ry   Z"is_observed_standalone_module_nodeÚresultr7   Zout_quant_idxsZcur_placeholder_node_idxZact_post_process_removed_graphr„   r…   r4   )r>   rc   rf   ri   rw   r8   rK   rƒ   r5   rŒ   ‘   s   þý


*þ@ þþ$()ÿÿ

ÿ
ÿþÿ
þ

	ÿÿ
ÿ
ÿ

ÿ
ÿ
ÿÿÿ
rŒ   )FNFT)BÚtypingr   r   r   r   r   r   r   Úcollectionsr	   r[   Ztorch.fxr
   r   r   Ztorch.fx.graphr   r   Ztorch.fx.noder   Zquantization_typesr   ry   r   Zmatch_utilsr   Zgraph_moduler   r   r   Zquantization_patternsr   Z	_equalizer   r   Úutilsr   r   r   r   r   r    r!   r"   Ztorch.ao.quantization.quantizer#   r$   r%   r&   r'   Z_opsÚopsr7   Zlinear_prepackZlinear_prepack_fp16Zconv1d_prepackZconv2d_prepackZconv3d_prepackrF   r6   rZ   rn   rN   rQ   rˆ   rŒ   r4   r4   r4   r5   Ú<module>   sJ   $(




ûþ9,þ    ý
ý