
    sgP                        d dl Z d dlZd dlmZmZmZmZmZmZm	Z	 d dl
Z
d dlmc mc mc mZ d dlmc mc m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 d dlmZ dd	lm Z m!Z! e
jD                  j                  Z# G d
 de jH                        Z%dedededee&ee    f   dee%e%f   f
dZ'dededee&ee    f   deee	e
jP                  e)f   e	e
jP                  e*f   f      fdZ+dededefdZ,dedede*fdZ-dedee*   fdZ.dedede&fdZ/de!de&de!fdZ0de!ddfdZ1d Z2e2de
jP                  de
jP                  de
jP                  fd       Z3e2de
jP                  de
jP                  de
jP                  fd       Z4e2de
jP                  de
jP                  de
jP                  fd        Z5dede6fd!Z7deded"e*defd#Z8y)$    N)CallableDictListOptionalSetTupleUnion)FakeQuantizeBaseObserverBase)_is_activation_post_process)getattr_from_fqn)GraphModule)Node   )NSNodeTargetTypeNSResultsTypec                       e Zd Z ej                         Z ej                         Z ej                         Z ej                         Z ej                         Z	y)NodeInputOrOutputTypeN)
__name__
__module____qualname__enumautoFP32INT8FP16UNKNOWNFP32_OR_INT8     G/var/www/html/venv/lib/python3.12/site-packages/torch/ao/ns/fx/utils.pyr   r      sE    499;D499;D499;DdiikG
 499;Lr    r   nodegm
logger_clsnode_type_to_io_type_mapreturnc                    |d   }|d   }|d   }|d   }|d   }|d   }	|d   }
|d   }| j                   d	k(  r| j                  |v r t        j                  t        j                  fS | j                  |v r t        j                  t        j                  fS | j                  |v r t        j
                  t        j
                  fS | j                  |v r4t        | |d
      }t        |t              sJ t        ||||      \  }}||fS t        j                  t        j                  fS | j                   dk(  r0| j                   dk(  sJ t        | j                  t              sJ t        || j                        t        fd|
D              }t        |t        t        f      s|r4t        | |d
      }t        |t              sJ t        ||||      \  }}||fS t        fd|D              }t        fd|	D              }|r t        j                  t        j                  fS |r t        j
                  t        j
                  fS t        j                  t        j                  fS | j                   dk(  r-| j                  dk(  rBt        | |d
      }t        |t              sJ t        ||||      \  }}|t        j                  fS | j                  dk(  rkt        | |d
      }t        |t              sJ t        ||||      \  }}t        | |d      }|t         j"                  u s
J | d       |t        j                  fS | j                  |v r4t        | |d
      }t        |t              sJ t        ||||      \  }}||fS t        j                  t        j                  fS t        j                  t        j                  fS )Nfuns_io_type_fp32funs_io_type_fp16funs_io_type_int8funs_io_type_fp32_or_int8mods_io_type_fp32mods_io_type_int8mods_io_type_fp32_or_int8meths_io_type_fp32_or_int8call_functionr   call_modulec              3   6   K   | ]  }t        |        y wN
isinstance.0target_typemods     r!   	<genexpr>z7get_node_first_input_and_output_type.<locals>.<genexpr>N   s      1
-8JsK(1
   c              3   6   K   | ]  }t        |        y wr3   r4   r6   s     r!   r:   z7get_node_first_input_and_output_type.<locals>.<genexpr>`         )
-8JsK()
r;   c              3   6   K   | ]  }t        |        y wr3   r4   r6   s     r!   r:   z7get_node_first_input_and_output_type.<locals>.<genexpr>c   r=   r;   call_method
dequantizetor   z handling needs to be added)optargetr   r   r   r   get_normalized_nth_inputr5   r   $get_node_first_input_and_output_typer   strr   anyr   r
   torchfloat16)r"   r#   r$   r%   FUNS_IO_TYPE_FP32FUNS_IO_TYPE_FP16FUNS_IO_TYPE_INT8FUNS_IO_TYPE_FP32_OR_INT8MODS_IO_TYPE_FP32MODS_IO_TYPE_INT8MODS_IO_TYPE_FP32_OR_INT8METHS_IO_TYPE_FP32_OR_INT8	first_arg_prev_node_input_typeprev_node_output_type"is_known_fp32_or_int8_input_moduleis_known_fp32_input_moduleis_known_int8_input_module	prev_nodecur_node_dtype_targetr9   s                       @r!   rE   rE   &   s    11DE01DE01DE 89T U01DE01DE 89T U!9:V!Www/!;;++)..0E0J0JKK;;++)..0E0J0JKK[[--)..0E0J0JKK[[550r1=Ii... 52z+C%% *+@AA)113H3P3PQQ	M	!ww-'''$++s+++r4;;/-0 1
<U1
 .
* sZ7GHI1 1r1=Ii... 52z+C%% *+@AA%( )
<M)
 &
" &) )
<M)
 &
" &)..0E0J0JKK')..0E0J0JKK)113H3P3PQQ	M	!;;,& 1r1=Ii... 52z+C%% *+@+E+EFF[[D 
 1r1=Ii... 52z+C%%
 %=T2q$I!%6E'((CDE6 *+@+E+EFF[[660r1=Ii... 52z+C%% *+@AA%--/D/L/LMM%--/D/L/LMMr    c                 N   t        | |d      }t        |t              sy|d   }d }|j                  dk(  r~|j                  t
        j                  k(  r |||dd      S |j                  t        j                  t        j                  t        j                  t        j                  fv r |||dd      S y|j                  d	k(  rt        |j                  t              sJ t        ||j                        t        t        j                  t        j                   t        j"                  t$        j&                  t        j(                  t        j*                  t        j,                  t        j.                  t        j0                  t        j2                  t        j4                  t        j6                  t        j8                  t        j:                  t        j<                  t        j>                  t        j@                  t        jB                  t$        jD                  t$        jF                  t$        jH                  t$        j&                  t$        jJ                  t$        jL                  f      rjN                  jP                  fS tS        fd
|D              }|rtU        |||      S y)z{
    Returns the qparams (scale, zero_point) of the first input to `node`,
    if they can be inferred from the graph.
    r   Nr.   c                 F   t        | ||      }t        | ||      }t        |t              rt        |j                  t              sJ t        |t              rt        |j                  t              sJ t        ||j                        }t        ||j                        }||fS r3   )rD   r5   r   rC   rF   r   )r"   r#   scale_arg_idx
zp_arg_idx
scale_nodezp_node	scale_objzp_objs           r!    _get_scale_zp_from_function_argsz@get_node_input_qparams.<locals>._get_scale_zp_from_function_args   s    -dBF
*4Z@*d+
:;L;Lc0RRR'4(Z-LLL$R):):;	!"gnn56""r    r0   r         r1   c              3   6   K   | ]  }t        |        y wr3   r4   )r7   r8   
module_objs     r!   r:   z)get_node_input_qparams.<locals>.<genexpr>   s      1
4?Jz;/1
r;   )+rD   r5   r   rB   rC   rH   quantize_per_tensortoqaddadd_relumulmul_relurF   r   nnqLinearConv1dConv2dnniq
ConvReLU2dConv3dBatchNorm2dBatchNorm3dConvTranspose1dConvTranspose2dELU	GroupNormInstanceNorm1dInstanceNorm2dInstanceNorm3d	LayerNorm	Hardswish	LeakyReLUReLU6BNReLU2dBNReLU3d
ConvReLU1d
ConvReLU3d
LinearReLUscale
zero_pointrG   get_node_input_qparams)r"   r#   r%   rX   rP   rb   rU   rf   s          @r!   r   r      s    )r15Ii& 89T U# ||&u8883Ir1aHH#''3<<#,,!OO3Ir1aHH 
	&)**C000%b)*:*:;








####""""""		1
: $$j&;&;<<-0 1
C\1
 .
* .))R9QRRr    c                     | j                   dk(  rt        || j                        }t        |      rt	        | j
                        dk(  sJ t        | j
                  d   t              sJ | j
                  d   } t        | j                  t              sJ t        || j                        }t        |      rHt	        | j
                        dk(  sJ t        | j
                  d   t              sJ | j
                  d   } | S )a  
    If node is not an observer, returns it.  If node is an observer,
    navigates up the graph and returns the first parent which is not an
    observer.  For example,

    graph: (node_non_obs), node = node_non_obs : returns node_non_obs
    graph: (node_non_obs -> obs0), node = obs0 : returns node_non_obs
    graph: (node_non_obs -> obs0 -> fq0), node = fq0 : returns node_non_obs
    r1   r   r   )	rB   r   rC   r   lenargsr5   r   rF   r"   r#   node_objs      r!   return_first_non_observer_noder      s     ww-#B4&x0tyy>Q&&&diilD11199Q<Ddkk3///'DKK8H*84499~***!$))A,555yy|Kr    c                     | j                   dk(  r1t        || j                        }t        |t        j
                        ryy)aO  
    Assumes that all non-param args occur first. Returns the number of
    non-param args expected for a node.  For example, for

      F.linear(x, weight, bias)

    Returns 1, because x is a non-param arg and weight and bias are params.
    For

      lstm_mod(x, hid)

    Returns 2, because both x and hid are non-param args.
    r1   rc   r   )rB   r   rC   r5   nnLSTMr   s      r!   get_number_of_non_param_argsr     s6    " ww-#B4h( r    c                     t        | j                        dk(  rg S | j                  dk(  r| j                  t        j
                  t        j                  j                  j
                  t        j
                  fv sO| j                  t        j                  t        j                  j                  j                  t        j                  fv rEg }t        d      D ]3  }t        | j                  |         t        k(  s#|j                  |       5 |S dgS )a-  
    Returns the indices of args of the node which we should attach
    loggers to, if input logging is enabled.

    For example,
    * for (x + y), returns [0, 1]
    * for (1 + y), returns [1]
    * for (x + 1), returns [0]
    * for (linear(x, w, b)) returns [0]
    * by default, returns [0]
    r   r0   rc   )r   r   rB   rC   rH   ri   ops	quantizedoperatorrk   rangetyper   append)r"   resultis      r!    get_arg_indices_of_inputs_to_logr   (  s     499~	ww/!		599#6#6#:#:HLLII;;599eii&9&9&=&=x||LLq 	!ADIIaL!T)a 	! 3Jr    c                    d}| j                   dv r!t        j                  | j                        }|S | j                   dk(  rGt	        | j                  t
              sJ t        || j                        }t        j                  |      }|S )z
    Returns a string representation of the type of the function or module
    pointed to by this node, or '' for other node types.
     )r0   r?   r1   )rB   rH   typenamerC   r5   rF   r   )r"   r#   r8   
target_mods       r!   get_target_type_strr   C  sv    
 Kww22nnT[[1
 	 
M	!$++s+++%b$++6
nnZ0r    results
model_namec                     i }| j                         D ]\  \  }}d}|j                         D ]5  }|j                         D ]   \  }}||k(  rt        |      sJ |d   d   }!" 7 ||||<   X|||<   ^ |S )a	  
    Rekeys the layer name of a results dictionary to use node names
    from `model_name`.

    For example, transforms

        {'base_op_1_0': {'node_output': {'model_a':
          [{'ref_node_name': 'linear1', ...}]}}}

    into

        {'linear1': {'node_output': {'model_a':
          [{'ref_node_name': 'linear1', ...}]}}}

    Note: we cannot use these node names directly because they are not
    guaranteed to be consistent across models. This is why we extract
    the results first and rekey afterwards.
    Nr   ref_node_name)itemsvaluesr   )	r   r   new_resultsold_layer_nameresult_type_to_resultsnew_layer_namemodel_name_to_resultscur_model_namelist_of_resultss	            r!   'rekey_logger_info_on_node_name_of_modelr   R  s    , K29--/ A..%;%B%B%D 	!3H3N3N3P /!Z////%4Q%7%HN	 %*@K'*@K'A r    c                    d}| j                         D ]L  }|j                         D ]6  }|j                         D ]   \  }}t        |      dkD  s|d   d   |} n  n  n |rw| j                         D ]c  }|j                         D ]N  }||   }|j                         D ]4  \  }}||k(  rt        t        |            D ]  }||   d   }|||   d<    6 P e yy)ay  
    If `fqn` entries are filled in for one of the models in `results`, copies
    them over to any models which do not have them filled out.

    A common use case benefitting from this is comparing a model prepared by
    quantization to a quantized model. In this case, the model prepared by
    quantization would have `fqn` entries, and the quantized model would not.
    Nr   fqn)r   r   r   r   )	r   model_name_with_fqnsr   r   r   model_resultsref_model_resultsr   r   s	            r!   maybe_add_missing_fqnsr   y  s-     ").."2 %;%B%B%D 	!-B-H-H-J )
M}%)$Q'.:/9,	
 	 	 &-nn&6 	6")?)F)F)H 6%$9:N$O!1F1L1L1N 6-J!%99 "3}#56 6/25925a(/666	6 r    c                       fdS )Nc                  f   | ^}}}t        |t              rt        |t              s t        |t              rFt        |t              r6g }t        ||      D ]#  \  }}||g|}|j	                   
|i |       % |S t        |t
        j                        rRt        |t
        j                        r8|j                  r|j                         }|j                  r|j                         }|j                  t
        j                  k7  s|j                  t
        j                  k7  ry ||g|} 	|i |S r3   )r5   tuplelistzipr   rH   Tensoris_quantizedr@   dtypefloat)r   kwargsa0a1a_otherr   el0el1new_argsfinners            r!   r   zGmaybe_dequantize_first_two_tensor_args_and_handle_tuples.<locals>.inner  s   Br5!jU&;r4 ZD%9GBK ;S/w/uh9&9:; NELL)jU\\.J]]_]]_ 88u{{"bhh%++&=%W%(%f%%r    r   )r   r   s   `@r!   8maybe_dequantize_first_two_tensor_args_and_handle_tuplesr     s    &2 Lr    xyc                     t        j                  |       }t        j                  | |z
        }dt        j                  ||z        z  S )z
    Computes the SQNR between `x` and `y`.

    Args:
        x: Tensor or tuple of tensors
        y: Tensor or tuple of tensors

    Return:
        float or tuple of floats
       )rH   normlog10)r   r   PsPns       r!   compute_sqnrr     s;     
AB	AE	BBG$$$r    c                 |    t        j                  | |z
  dz  j                         | dz  j                         z        S )z
    Computes the normalized L2 error between `x` and `y`.

    Args:
        x: Tensor or tuple of tensors
        y: Tensor or tuple of tensors

    Return:
        float or tuple of floats
    rc   )rH   sqrtsumr   r   s     r!   compute_normalized_l2_errorr     s3     ::A!|((*adZZ\9::r    c                     | j                  dd      } |j                  dd      }t        j                  j                  j	                  | |      S )z
    Computes the cosine similarity between `x` and `y`.

    Args:
        x: Tensor or tuple of tensors
        y: Tensor or tuple of tensors

    Return:
        float or tuple of floats
    r   )reshaperH   r   
functionalcosine_similarityr   s     r!   compute_cosine_similarityr     sA     	
		!RA			!RA8800A66r    c                     | j                   dk(  ri| j                  t        j                  t        j                  t
        j                  t
        j                  t        j                  t        j                  fv ryy)Nr0   FT)rB   rC   rH   ri   rk   r   catstack)r"   s    r!   op_type_supports_shadowingr     sQ    ww/!;;IIIILLLLIIKK
 
 r    idxc                 D   	 | j                  |d      }|P|\  }}t        |      t        |      z   |kD  sJ |t        |      k  r||   S t        |j                               |   S t        | j                        t        | j
                        z   |kD  sJ |t        | j                        k  r| j                  |   S |t        | j                        z   }t        | j
                  j                               |   S # t        $ r t        | j                        t        | j
                        z   |kD  sJ |t        | j                        k  r| j                  |   cY S |t        | j                        z   }t        | j
                  j                               |   cY S w xY w)zu
    Given a node, gets the n'th input to that node, normalizing
    args and kwargs to the best of its ability.
    T)normalize_to_only_use_kwargs)normalized_argumentsr   r   r   r   r   RuntimeError)r"   r#   r   norm_args_and_kwargs	norm_argsnorm_kwargs
kwargs_idxs          r!   rD   rD     st   
:#88T  9  
  +%9"I{y>C$44s:::S^# ~% K..01#66tyy>C$44s:::S^#yy~% 3tyy>1
DKK..01*== 	: 499~DKK 003666TYY99S>!s499~-J**,-j99	:s,   AC< C< 'AC< >=C< <A F>FF)9r   r   typingr   r   r   r   r   r   r	   rH   torch.ao.nn.intrinsic.quantizedaor   	intrinsicr   rq   torch.ao.nn.quantizedrm   torch.nntorch.ao.quantizationr
   r   torch.ao.quantization.observerr   torch.ao.quantization.utilsr   torch.fxr   torch.fx.graphr   ns_typesr   r   r   rh   Enumr   rF   rE   r   r   intr   r   r   r   r   r   r   r   r   r   r   boolr   rD   r   r    r!   <module>r      s     D D D  . . # #  @ F 8    5 ii
	DII 	xN
xNxN xN #3,<(=#=>	xN
  "778xNvM
MM #3,<(=#=>M eE%,,-.ellC6G0HHIJ	M`
 
:
 	44 DI 6d   $$$ $N6M 6d 6D: :%ELL %U\\ %ell % :%  :;5<< ;ELL ;U\\ ; :; :7 7%,, 75<< 7 :7&T d !:4 !:[ !:s !:t !:r    