a
    d                    @   s6  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	 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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!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/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5 d dl6m7Z7 d dl8m9Z9 ddl(m:Z:m;Z;m<Z<m=Z= ddl>m?Z?m@Z@mAZA ddlBmCZCmDZDmEZE d
dlFmGZGmHZH d dlImJZJ d dlKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZT g dZUeVeWejXdgZYejZj[jj\j]ejZj[jj\j]dZ^ejZj[jj_j]ejZj[jj_j]dZ`eeMeaejbjcf eXdddZdeOeT eQeOeje eXf dd d!Zfe	eeeDeCeXd"d#d$ZgeeeDeXd%d&d'ZheeMeaejbjcf d(d)d*ZieOe eOeNe  eeCeXd+d,d-ZjeeMeaejbjcf eGeeOeC eQeeQeLd.f eGeOeC f d/d0d1ZkejbjceMeeRejbjc f dd2d3d4ZleePea d5d6d7ZmeeejbjceMeaejbjcf eed8d9d:ZneeeeCeMeaejbjcf eMeeXf ePe dd;d<d=ZoeeeMeaejbjcf eMeeXf eMeaeOeQeSejeepf eXf  f d>d?d@ZqeeMeaejbjcf eOeSejeepf  dAdBdCZreeeMeaejbjcf eCeOeSejeepf  dDdEdFZseeeMeaejbjcf eCeXdDdGdHZteSeeLf e	eejbjceMeaejbjcf eeOe eGeCe	dI
dJdKZueeejbjceMeaejbjcf eeOe eGeCddL	dMdNZveeLejbjceMeaejbjcf eeXeCddOdPdQZweejbjceMeaejbjcf eeMeae&f eLeOe eXeOe dR	dSdTZxeeNeV eMeaef ejbjceMeaejbjcf eddUdVdWZyeeSejeepf eMeae&f ddXdYdZZzeeMeae&f dd[d\d]Z{eejbjceMeaejbjcf eXd^d_d`Z|eejbjceMeaejbjcf dadbdcZ}eeeMeaejbjcf eGdddedfZ~eeMeae&f eMeaef eGeMeaeLf eCePea eXeOe dg	dhdiZejbjceXeMeaejbjcf eLeGeCddjdkdlZeeMeaef eMeaeQeaepf f eGeMeaeLf eeXePea ddm	dndoZdteeSeeMeaeLf f eXeMeaeQeaepf f eQeLd.f eSeGeMeaeLf df eSeeMeaeLf df eSeCeMeaeLf df eXedq
drdsZdS )u    N)GraphModule)GraphNode)Argument   )propagate_qconfig_)ObserverBase_is_activation_post_process)_is_reuse_input_qconfig
QConfigAny)QConfigMapping   )_generate_node_name_to_qconfig_update_qconfig_for_fusion_get_flattened_qconfig_dict_update_qconfig_for_qat)_default_root_node_getter!_get_pattern_to_quantize_handlersQuantizeHandler)PatternNodePattern)is_equalization_observernode_supports_equalization)_sorted_patterns_dict)_MatchResultWithQConfig_find_matches)3_insert_dequant_stubs_for_custom_module_lstm_output_is_custom_module_lstm+_maybe_get_custom_module_lstm_from_node_arg+_qconfig_satisfies_dtype_config_constraintsget_custom_module_class_keysall_node_args_have_no_tensorsassert_and_get_unique_device(get_non_observable_arg_indexes_and_typesget_new_attr_name_with_prefixnode_arg_is_weightnode_arg_is_biasNON_QUANTIZABLE_WEIGHT_OPSObservedGraphModuleAttrs)PlaceholderObserverconvert)_parent_nameget_qconfig_dtypesget_swapped_custom_module_class"activation_is_statically_quantized)get_pattern_to_dtype_configsget_module_to_qat_module&get_fusion_pattern_to_root_node_getter)BackendConfigDTypeConfigget_native_backend_config)PrepareCustomConfigStandaloneModuleConfigEntry)
FakeTensor)	AnyDictListOptionalSetTupleTypeUnionCallable)insert_observers_for_modelprepare propagate_dtypes_for_known_nodesinput_act_obs_or_fq_ctroutput_act_obs_or_fq_ctr)nodenamed_modulesreturnc                 C   s*   t | tjjo(| jdko(t|t| j S )Ncall_module)
isinstancetorchfxr   opr	   strtargetrH   rI    rS   i/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torch/ao/quantization/fx/prepare.py _is_activation_post_process_node   s    rU   )obs_or_fq_ctrrJ   c                 C   s(   | du rdS |  }|j t|ddfS dS )zh Given a constructor for observer or fake quant module, returns
    a Tuple of dtype and is_dynamic
    N)NF
is_dynamicF)dtypegetattr)rV   Z	obs_or_fqrS   rS   rT   _get_dtype_and_is_dynamic   s    rZ   )argrH   qconfigdtype_configbackend_configrJ   c                    s>  t | ttfr*t fdd| D S t | ts8dS t|  }t|  }| oZ| }|rjd d}t	|\}	}
j
du pj
|	kotjt|
kotjS |rjd dd}t	|\}}j}||k}tjdd	}|du p|o|S jd d
d}t	|\}}j}|du p8||kS dS )z] Check if the configured qconfig for the argument
    is supported by the backend or not
    c                 3   s   | ]}t | V  qd S N)(_is_input_arg_dtype_supported_by_backend).0ar^   r]   rH   r\   rS   rT   	<genexpr>   s
   z;_is_input_arg_dtype_supported_by_backend.<locals>.<genexpr>Ttarget_dtype_inforF   Nweight_obs_or_fq_ctrF)is_activationbias_obs_or_fq_ctr)rL   listtupleallr   r%   r&   metagetrZ   Zinput_dtypeboolrW   r   Zinput_dtype_with_constraintsweight_dtypeZweight_dtype_with_constraints
bias_dtype)r[   rH   r\   r]   r^   	is_weightis_biasrg   rF   qconfig_dtypeqconfig_is_dynamicrf   qconfig_weight_dtype_Zbackend_config_weight_dtypedtype_matchesqconfig_satisfies_constraintsrh   qconfig_bias_dtypeZbackend_config_bias_dtyperS   rc   rT   r`      s>    




r`   )rH   r\   r]   rJ   c           	      C   sT   |j }d}| jd d}t|\}}|r0tj}||k}t||j}|du pR|oR|S )z[ Check if the configured qconfig for the output
    is supported by the backend or not
    Nre   rG   )Zoutput_dtyperl   rm   rZ   rM   float32r   Zoutput_dtype_with_constraints)	rH   r\   r]   Zbackend_config_output_dtypeZqconfig_output_dtyperG   Zqconfig_output_is_dynamicrw   rx   rS   rS   rT   %_is_output_dtype_supported_by_backend   s    	r{   rR   c                 C   sJ   t | |}t| jdkrFt| jd trF|tjkrF| jd jdkrFdS dS )z Check if observer in same graph
    when the node output is not fp32 and input is 'placeholder'
    the input is assumed to be quantized, so it is observed
    in a different place rather than not observed.
    r   placeholderFT)_get_arg_target_dtype_as_outputlenargsrL   r   rM   quint8rO   )rH   rI   Znode_output_dtyperS   rS   rT   _is_observer_in_same_graph   s
    
r   )patternmatched_node_patternr\   r^   rJ   c                 C   s   |du s| du rdS |dur(t |dks,J t|}|| g }t|}|| t}||}|}	|d }
|D ]T}d}t|	jt|	j  D ]}|ot	||	|||}q|ot
|
||}|rl dS qldS )z Check if the dtype configuration of a pattern is supported by
    the backend or not, and whether the qconfig satisfies constraints
    specified in the corresponding dtype config.
    NTr   r   F)r~   r0   rm   r2   r   ri   r   kwargsvaluesr`   r{   )r   r   r\   r^   Zpattern_to_dtype_configsZdtype_configspattern_to_root_node_getterroot_node_getter	root_nodeZ
input_nodeZoutput_noder]   	supportedr[   rS   rS   rT   9_is_pattern_dtype_config_and_qconfig_supported_by_backend   s,    

r   .)rH   rI   prepare_custom_configparent_qconfigparent_backend_configrJ   c                 C   sz   t | j}t|| }tdddd}|j||}|j||}|jpPt 	|}|j
}	|jpbt }|jpl|}
||	||
fS )z
    Returns the standalone module QConfigMapping and PrepareCustomConfig
    for `node`, assuming that the module pointed to by `node` is
    a standalone modules.
    NrS   )rP   rQ   typer7   standalone_module_classesrm   standalone_module_namesqconfig_mappingr   Z
set_globalexample_inputsr   r6   r^   )rH   rI   r   r   r   module_namemodule_typeZconfig_entryr   r   r^   rS   rS   rT   _get_standalone_module_configs  s    

r   )rootmodule_to_qat_modulerJ   c                 C   s   t | |ddd d S )NTF)mappingZinplaceZremove_qconfigr*   )r   r   rS   rS   rT   _qat_swap_modules!  s    r   )r   sc                 C   s>   t | tr|| j n"t | ttfr:| D ]}t|| q*d S r_   )rL   r   addnameri   rj   _add_matched_node_name_to_set)r   r   
maybe_noderS   rS   rT   r   &  s
    
r   )rH   observermodelrI   graphrJ   c           
      C   s   t |}|r|| t|r*| jd }nd}t|}||}t||| |||< || " |d|| fi }	W d   n1 s0    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_rK   N)r"   tor   r   r$   setattrZinserting_afterZcreate_node)
rH   r   r   rI   r   Zmodel_deviceprefixZget_new_observer_nameZobserver_nameZnew_obsrS   rS   rT   _insert_observer-  s    

"r   )r   	last_noder\   r^   rI   cache_for_no_tensor_checkprocessed_nodesrJ   c           
   	   C   s   t | ttfr.| D ]}t||||||| qnVt | trt | tsFJ | }||v rVdS || |du rldS t||||}	|	|jd< dS )z Sets the target_dtype_info for each node in matched_node_pattern
    Note: processed_nodes is used to ensure we only process each node once
    Nre   )rL   ri   rj   /_set_target_dtype_info_for_matched_node_patternr   r   %_get_target_activation_dtype_for_noderl   )
r   r   r\   r^   rI   r   r   Znode_patternrH   re   rS   rS   rT   r   I  s6    

r   )rH   r\   rI   r   rJ   c           
      C   s   t | ||}|rdddS |dur~t|\}}}|s8|ntj}|tjkr\|tjkr\|s\tjntj}	|j|jtj|	d|jdS t		t
S )a<  
    For each op attribute in the op's input activation, output activation,
    weight, bias - returns the settings of dtype and is_dynamic we expect
    for the `quantize` call in the reference model representation, or None
    if there is no `quantize` call needed.

    For example, if we have a node corresponding to `op0` in

      x0 -> op0 -> x1

    And we want a reference quantized representation to be

      x0 -> quant_static -> dequant -> op0 -> quant_dynamic -> dequant -> x1

    Then this function will return

      {
        "input_act_obs_or_fq_ctr": MinMaxObserver.with_args(dtype=torch.quint8, is_dynamic=False),
        "output_act_obs_or_fq_ctr": MinMaxObserver.with_args(dtype=torch.quint8, is_dynamic=False),
      }

    TODO(future PR, if needed): explicitly spell out the non-Tensor
    dtypes.
    NrE   )rX   )rF   rf   rh   rG   )r!   r-   rM   floatfloat16
activationweightr)   Z	with_argscopy+_DEFAULT_FP32_QCONFIG_FOR_TARGET_DTYPE_INFO)
rH   r\   rI   r   args_have_no_tensorsZ	act_dtypero   Zinput_act_is_dynamicoutput_act_dtyperp   rS   rS   rT   r   }  s:    
r   )r[   rI   rJ   c                 C   s   t | tsJ t| |}d}|dur4|jd d }nDt| |rj| jd }t |tsZJ d|jd d }n| jd d }t|\}}|S )a   Get the target output activation dtype for
    the argument in the original graph, skipping inserted observers
    We are assuming that the observers are inserted correctly, and the dtype for
    argument in quantized graph will match what is specified by the qconfig
    Nre   rG   r   z(Currently we only support observing Node)rL   r   r   rl   rU   r   rZ   )r[   rI   Zcustom_module_lstm_noderG   Zobserved_argr   rv   rS   rS   rT   r}     s    	


r}   )r[   rH   rI   r^   rJ   c                 C   s   t | tsJ t|| |}t|| |}| o0| }|rV|jd d}t|\}}	|S |r|jtv rhdS |jd dd}
t|
\}}	|S n"|jd dd}t|\}}	|S dS )W Get the target argument dtype for the argument `arg`, as input
    to node `node`
    re   rF   Nrf   rh   )	rL   r   r%   r&   rl   rm   rZ   rQ   r'   )r[   rH   rI   r^   rq   rr   rg   rF   rs   rv   rf   ru   rh   ry   rS   rS   rT   &_get_arg_target_dtype_as_input_to_node  s"    	
r   c           
      C   sl   t | tsJ t|| |}t|| |}| o0| }|rdd|jd v rd|jd d}t|\}}	|	S dS dS )r   rF   re   FN)rL   r   r%   r&   rl   rm   rZ   )
r[   rH   rI   r^   rq   rr   rg   rF   rv   rt   rS   rS   rT   +_get_arg_target_is_dynamic_as_input_to_node  s    	r   )
rH   r[   r\   r   rI   r   qhandlerr   r^   rJ   c	                  C   s6  t |ttfrJg }	|D ]&}
t| |
|||||||	}|	| qt||	S t |tsX|S t |tsfJ |}|duox| }|dusJ |st| ||}t	|}|r|j
n|j}t||}t|| ||}t|| ||}| r||kr|tjkr|tvr| p|o|| jd u }nt| ||||\}}}}|j}d}t| jD ]\}}||u r@|} q`q@|du rpd}n4t||}||v rtjntj}||ko|tjk}|j}|r2| }d}|j D ]H\}}|jdkr||j }t|t|kr|j|kr|} qq|du r.t|||||}|}n|}|S )zk
    Given a `node` and an `arg`, inserts an input observer between
    `node` and `arg` if necessary.
    Nr   FrK   )rL   ri   rj   -_maybe_insert_input_observer_for_arg_or_kwargappendr   r   is_standalone_moduler%   r
   r   r   r}   r   r   rM   r   _DO_NOT_OBS_DTYPE_LISTr   r   input_quantized_indexes	enumerater   usersitemsrO   rQ   rX   r   ) rH   r[   r\   r   rI   r   r   r   r^   Znew_arg_to_returnZ	inner_argZnew_inner_argnew_argr   rq   _is_reuse_input_qconfig_Zact_post_process_ctrZarg_as_output_target_dtypeZarg_as_input_target_dtypeZarg_as_input_target_is_dynamicZ	needs_obsrv   sm_prepare_custom_configZsm_input_quantized_idxsZcur_input_idxZarg_idxZarg_to_checkZnew_obs_modZexisting_obs_nodeZmaybe_obs_nodeZmaybe_obs_modZnew_obs_noderS   rS   rT   r     s    



	











r   )	rH   r\   r   rI   r   r   r   r^   rJ   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)r   r   r   r   r   rj   )rH   r\   r   rI   r   r   r   r^   new_argsr[   r   Z
new_kwargskkwargZ	new_kwargrS   rS   rT   &_maybe_insert_input_observers_for_node  s.    


r   )rH   equalization_qconfigr   rI   r   	is_branchr^   rJ   c                 C   s   |du st | |sdS |r0td|  d dS g }| jD ]b}t|trTt| ||r`|| q:t| ||}	|	rv|j	n|j
}
|
 }t|||||}|| 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warnr   rL   r   r&   r   r%   r   Zinput_activationr   rj   )rH   r   r   rI   r   r   r^   r   r[   rq   Zact_eq_process_ctrZnew_eq_obs_modZnew_eq_obs_noderS   rS   rT   3_maybe_insert_input_equalization_observers_for_node  s,    




r   )	rH   r   rI   r   &node_name_to_match_result_with_qconfigmatched_patternr   is_qatrJ   c                 C   s   | | jd\}}	}
}}|du r$dS |dus0J | jdksBJ d|duoP| }| jd  d}t|\}}	|ttjg v}|ot	|}|o| }|r|
 }t| ||||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.
    NNNNNNoutputz3observer insertion for outputs is handled elsewherere   rG   )rm   r   rO   r   rl   rZ   r   rM   r   r/   r   r   )rH   r   rI   r   r   r   r   r   r   rv   r   r\   r   rG   rs   Zshould_insert_observerr   rS   rS   rT   &_maybe_insert_output_observer_for_node  s*    r   )graph_output_nodeoutput_quantized_idxsnode_name_to_qconfigr   rI   r   rJ   c           	   
      s   |dgks|g ksJ d|g kr&dS t j}tt jtttf t jjttt jjf t	td fdd g }| j
D ]}| |||||| qnt|| _
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)r   target_dtyper   r   rI   r   rJ   c              
      s   t | trZt| |}||krT|| j}|dus8J d| }t| ||||}	|	S | S nt | ttfrg }
| D ]}|
	 |||||| qpt | tr|
S t|
S n>t | t
ri }|  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)rL   r   r}   rm   r   r   r   ri   rj   r   dictr   )r   r   r   r   rI   r   Zthis_node_dtyper\   Zobserver_modZobserver_noderesultsZ
inner_nodeZresults_dictr   Zinner_v&_recursive_maybe_replace_node_with_obsrS   rT   r   C  s@    






z[_maybe_insert_observers_before_graph_output.<locals>._recursive_maybe_replace_node_with_obs)rM   r   r   rX   r:   rP   r   nnModuler   r   r   rj   )	r   r   r   r   rI   r   Zoutput_target_dtyper   Zold_argrS   r   rT   +_maybe_insert_observers_before_graph_output'  s,    
;
r   )rH   r   r   rJ   c           	      C   sh   d| j d d< d| j d d< || jd\}}}}}|durd| rd| jd }t|trdt||| dS )z
    Assigns `target_dtype` to `node`, setting `is_dynamic` to False. If `node`
    is a general tensor shape op, also call this function recursively on
    the first argument, to propagate the dtype to the caller.
    Nre   rF   rG   r   r   )rl   rm   r   is_general_tensor_value_opr   rL   r   _maybe_propagate_dtype_for_node)	rH   r   r   r   rv   r   r   r\   Z	prev_noderS   rS   rT   r     s    


r   )r   r   rJ   c           
      C   s   | j D ]z}t|}|D ]h}|| |}|D ]R}|j| }t|ttfrPt|}n|g}|D ] }	t|	tjjj	rZt
|	|| qZq*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)nodesr#   r   rL   rj   ri   rM   rN   rH   r   r   )
r   r   rH   Znon_observable_arg_dictZarg_typeZnon_observable_indicesindexr[   arg_listZcur_argrS   rS   rT   rD     s    


rD   )rH   r   rI   rJ   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||st|tsdS |jdkrdS d}t t|jD ]}|j| }t|tr qq|du rdS |}|d7 }|dkrxt	dqxt|tsJ |j
}t|tsJ || }	t|ttfrt|D ]\}
}|
dkrTq>d}t||st|jdk rz dS |jd }|d7 }|dkrXt	dqXt|j
\}}t|| ||	 q>| j D ]8\}}t||sJ t|j
\}}t|| ||	 qd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)ranger~   r   rL   r   ri   rj   rU   rO   AssertionErrorrQ   rP   r   r,   r   r   r   )rH   r   rI   Z	first_argiZfirst_arg_argZiteration_guardZtrace_back_nodeZtarget_to_useZobs_mod_to_useZ	input_idxZ	input_argparent_namer   output_obs_noderv   rS   rS   rT   (_maybe_make_input_output_share_observers  sh    











r   )rH   r   rI   c                 C   sD   t | j }|D ],\}}t||s(J ||  |j| qd S r_   )ri   r   r   rU   Zreplace_all_uses_withr   Z
erase_node)rH   r   rI   r   r   rv   rS   rS   rT   _remove_output_observer  s
    
r   )rH   r\   rI   r   c           
      C   sH   || j  }|j}t|||}||}t| j \}}	t|| |	| d S r_   )rQ   float_to_observed_mappingr.   
from_floatr,   r   )
rH   r\   rI   r   Zcustom_moduleZcustom_module_class_mappingZobserved_custom_module_classZobserved_custom_moduler   r   rS   rS   rT   _swap_custom_module_to_observed(  s    
r   )	r   r   r   r   equalization_config_mapr^   observed_node_namesr   rJ   c           2   
   C   s  i }t | jdd}	|j}
|j}t }| jjD ]}tt|j	d< q.d}d}i }i }| jjD ]8}|j
dkrz|||< |d7 }|j
dkr\|||< |d7 }q\| D ]6\}}|\}}}}}|dusJ t|||||	|| q| jjD ]}|j
dkr|| |
v rtt|j	d< q|j
d	v r>t||	|}|rdddd
|j	d< q|j
dkr|| |v rtt|j	d< qt| j| t }| D ]\}}|\}}}}}t||||}|dusJ t|j	d d \}}|s|dtttjfvrt||tjjjj||	|| qt| jj}t }d}d}d}|D ]X}|j
dkr:n|j
dv rN||jd\}}}}}||jd} |j	d }!d|j	v r|!duot|j	d t}"n|!du}"|du s|" o|j
dk }#t||||}|#sN|rNt | jdd}	|j
dkr:|dusJ t|| d}$t |j!dkrt|j!d t"rt |j!d j#dkr|j!d j#D ]N}%||%jddup|%j
dkot|	t$|%j% t&}&|%|krZ|&rZd}$qZt'|}'|'|t(}(|(|})||)u }*|*rt)||| |	| j||| t*|| | |	| j|$| ||u }+|duo|+ },t,|}-|+rNt-||	||rrt.|| |	| j |j%|vr8|/|j% t0|||	| nt1|| |	| j||||}.|.durNt|j#2 }/|/D ] }0|0|.u rq|03||. qt4||	}1|,r|1s|-rt5|| |	st6|| |	 |durN|7 rN|j%|vrN|/|j% t0|||	| nt8|||| |	| j |j
dkrd|d7 }n|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.
    FZremove_duplicatere   r   r|   r   r   N)rK   call_methodcall_functionrE   rG   )rK   r   r   r   r   valrK   T)9r   rI   r   output_quantized_indexessetr   r   r   r   rl   rO   r   r   -_DEFAULT_QUINT8_QCONFIG_FOR_TARGET_DTYPE_INFOr!   rD   r   rZ   intr   rM   rn   aoquantizationr\   !_default_fp32_placeholder_qconfigri   rm   r   rL   r8   r   r~   r   r   r   rP   rQ   r   r2   r   r   r   r   r
   r   r   r   r   r   keysZreplace_input_withr   r   r   Zis_custom_moduler   )2r   r   r   r   r   r^   r   r   r   rI   input_quantized_idxsr   r   rH   Zinputs_seen_counterZoutputs_seen_counterZplaceholder_node_to_input_indexZoutput_node_to_output_index	node_nameZmatch_res_with_qconfigr   r   r   r   r\   r   Zis_supported_by_backendr   rv   Znodes_before_observationZ#custom_module_names_already_swappedZresults_noder   Zthis_node_dtype_infoZoutput_is_a_tensorZskip_inserting_observersZis_quantized_branchuserZis_user_quantizedr   r   r   Zis_input_node_of_the_patternZis_last_node_of_patternr   r   Zmaybe_output_obs_nodeZ
orig_usersZ	user_nodeZ_is_observer_in_same_graph_rS   rS   rT   rB   7  sJ   <












rB   )r   r   rI   r   r   r^   rJ   c              	   C   s   |  D ]\}\}}}	}
}|
du r&qn
|
 s0qt|||||\}}}}||j }tjjjj}|||||||d}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)r   r   r^   )r   r   r   rQ   rM   r   r   Zquantize_fxZ_prepare_standalone_module_fxr,   r   )r   r   rI   r   r   r^   r   r   rv   r   r   r\   Zsm_qconfig_mappingZsm_example_inputsr   Zsm_backend_configZstandalone_modulerC   Zobserved_standalone_moduler   r   rS   rS   rT   %_run_prepare_fx_on_standalone_modules  s8    


r   )	observedr   node_name_to_scoper   !equalization_node_name_to_qconfigr   r   r   rJ   c              	   C   s    t |||||||d| jd< d S )N)r   r   r   r   r   r   r   _observed_graph_module_attrs)r(   rl   )r   r   r   r   r   r   r   r   rS   rS   rT   _save_state  s    r  F)
r   r   r   r   r   r   _equalization_configr^   r   rJ   c	              	   C   s  |du rt  }|du rt }t|tr:td t|}t|trXtd t|}t|trvtd t |}t|trtd t|}t|tsJ t|tsJ t	|}t	|}i }	|du rt
 }t|}	t|	}	t|}
t| | t| | t|}t| ||  |r<t|}t| | t|| t| jdd}t| || j||}t| || j||}t|j }t|j }t|j}t| j||	|
|||}i }|  D ]$\}}g ||| R }|||< qt!| ||||| t" }t#| |||||||}t$| | j} t%| ||||||| |r|dusBJ t|j&d t's\J d	|j(}|j)}| j*d
 }d|_+||_,||_-| S )a:   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 related to standalone module
        in model.meta["_observed_graph_module_attrs"]:
            is_observed_standalone_module (bool): boolean value that shows whether the
            current model is a observed standalone module or not
            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
    NzPassing a QConfig dictionary to prepare is deprecated and will not be supported in a future version. Please pass in a QConfigMapping instead.zPassing a QConfig dictionary to prepare for equalization is deprecated and will not be supported in a future version. Please pass in a QConfigMapping instead.zPassing a prepare_custom_config_dict to prepare is deprecated and will not be supported in a future version. Please pass in a PrepareCustomConfig instead.zPassing a backend_config_dict to prepare is deprecated and will not be supported in a future version. Please pass in a BackendConfig instead.Fr   r   zVstandalone module only supports returning simple value currently(not tuple, dict etc.)r   T).r6   r   rL   r:   r   r   	from_dictr3   r   deepcopyr5   r   r   r2   r   r   r   to_dictr1   r   r   r   rI   r   r   ri   r   r   r   r    r   r   r   r   r   rB   r   r  r   r   r   r   rl   Zis_observed_standalone_moduleZ&standalone_module_input_quantized_idxsZ'standalone_module_output_quantized_idxs)r   r   r   r   r   r   r  r^   r   Zpattern_to_quantize_handlerZroot_node_getter_mappingZflattened_qconfig_dictr   rI   r   r   r   r   Zcustom_module_classesZmatches_without_qconfigr   r   Zmatch_without_qconfigZmatch_with_qconfigr   Zresult_noder   r   Zobserved_graph_module_attrsrS   rS   rT   rC     s    !













	



rC   )NNNF)r   rM   r   Ztorch.fxr   Ztorch.fx.graphr   r   Ztorch.fx.noder   quantizer   r   r   r	   r\   r
   r   r   r   Zqconfig_mapping_utilsr   r   r   r   Zquantize_handlerr   r   r   Ztorch.ao.quantization.utilsr   r   Z	_equalizer   r   Zpattern_utilsr   Zmatch_utilsr   r   utilsr   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   Ztorch.ao.quantizationr)   Ztorch.ao.quantization.quantizer+   r,   r-   r.   r/   Zbackend_config.utilsr0   r1   r2   r^   r3   r4   r5   Zcustom_configr6   r7   Ztorch._subclassesr8   typingr9   r:   r;   r<   r=   r>   r?   r@   rA   __all__r   r   rn   r   r   r   r   r   r   Z#_default_quint8_placeholder_qconfigr   rP   r   r   rU   rX   rZ   r`   r{   r   r   r   r   r   r   r   r   r   r}   r   r   r   r   r   r   r   r   rD   r   r   r   rB   r   r  rC   rS   rS   rS   rT   <module>   s  <,"/
#
5
 D
 5-
/
a

%^


  f*

    
