
    shEN                     H   S SK JrJrJrJr  S SKrS SKJs  Js  J	r
  S SKJs  Js  J	s  Jr  S SKJr  S SKJr  S SKJr  \R&                  \
R&                  \R(                  \R(                  1rS\\\\4   \\   4   S\S\S\\   4S	 jrS
\\\4   S\\\4   S\\\\\R4                  4   4   4S jr S+S\R8                  S\\\4   S\SS4S jjrS+S\R8                  S\S\\\4   4S jjr " S S\R8                  5      r " S S\5      r  " S S\5      r!S\S\4S jr"S\S\4S jr# " S S\R8                  5      r$S\R8                  S\R8                  S\%\&   S \SS4
S! jr'S" r(\ S#.S$\R8                  S%\R8                  S\%\&   S\\\4   4S& jjr)S\R8                  S\R8                  S\\\\\R4                  4   4   4S' jr*\!S4S\R8                  S\R8                  SS4S( jjr+\!SS).S$\R8                  S%\R8                  S\\\\\R4                  4   4   4S* jjr,g),    )AnyCallableOptionalUnionN)prepare)&get_default_compare_output_module_liststr_listkey_strpostfixreturnc                 x   UR                  S5      nUS   U:X  Ga  SR                  UR                  S5      SS 5      nU  H[  nSR                  UR                  S5      SS 5      nSR                  UR                  S5      SS 5      nXF:X  a  Us  $ XG:X  d  MY  Us  $    US:X  a  SR                  UR                  S5      SS 5      n[        U5      S:X  a  g U  H[  nSR                  UR                  S5      SS 5      nSR                  UR                  S5      SS 5      nXF:X  a  Us  $ XG:X  d  MY  Us  $    g g )N. r   _packed_params)splitjoinlen)r	   r
   r   	split_strmatch_strings2pattern1pattern2s           n/Users/tiagomarins/Projetos/claudeai/copy_bank/venv/lib/python3.13/site-packages/torch/ao/ns/_numeric_suite.py_find_matchr      s1   
 c"I}www}}S1!B78Bwwrxx}Qr23Hwwrxx}Qr23H'	'	  &&777==#5a#;<L< A%77288C=2#6777288C=2#67+I+I      
float_dictquantized_dictc                    [         R                  R                  S5        0 nU GH/  n[        XS5      nUb  0 X#'   X   X#   S'   X   X#   S'   M+  [        XS5      nUb  0 X#'   X   X#   S'   X   S   X#   S'   UR	                  S5      nUS	   S
:X  d  Mo  US   S:X  d  Mz  US   nSR                  USS 5      nUS-   U-   nUS-   U-   n	X;   d  M  X;   d  M  0 X#'   X   X#   S'   X   R                  5       S   S   S   R                  5       S   S   X#   S'   X	   X#   S'   X   R                  5       S   S   S   R                  5       S   S   X#   S'   GM2     U$ )a  Compare the weights of the float module with its corresponding quantized
module. Return a dict with key corresponding to module names and each entry being
a dictionary with two keys 'float' and 'quantized', containing the float and
quantized weights. This dict can be used to compare and compute the quantization
error of the weights of float and quantized models.

Example usage::

    wt_compare_dict = compare_weights(
        float_model.state_dict(), qmodel.state_dict())
    for key in wt_compare_dict:
        print(
            key,
            compute_error(
                wt_compare_dict[key]['float'],
                wt_compare_dict[key]['quantized'].dequantize()
            )
        )

Args:
    float_dict: state dict of the float model
    quantized_dict: state dict of the quantized model

Return:
    weight_dict: dict with key corresponding to module names and each entry being
    a dictionary with two keys 'float' and 'quantized', containing the float and
    quantized weights
z/quantization_api._numeric_suite.compare_weightsweightNfloat	quantizedr   r   r   r   param_all_weight_valuesr   z.weight_ih_lz.weight_hh_l      )torch_C_log_api_usage_oncer   r   r   __getstate__)
r   r   weight_dictkey	match_keyr   layermodule_namefloat_weight_ih_keyfloat_weight_hh_keys
             r   compare_weightsr4   7   s   > 
HH  !RS#%K
:	 !K(2(=KW%,:,?K[)  
1AB	 !K(2(=KW%,:,?,BK[) IIcN	R=G#	"9M(MbME((9Sb>2K"-">"F"-">"F"05H5V#% ,6,K )"'446q9!<Q?LLNqQRST  - -7,K )"'446q9!<Q?LLNqQRST  -; B r   modtarget_dictprefixc                 
   S nU R                  5        H3  u  pE[        U[        5      (       d  M  UR                  X" U5      S-   '     O   U R                  5        H%  u  pEU(       a  U" U5      U-   OUn[	        XQU5        M'     g)zThis is the helper function for get_logger_dict

Args:
    mod: module we want to save all logger stats
    prefix: prefix for the current module
    target_dict: the dictionary used to save all logger stats
c                     U S:X  a  U $ U S-   $ )Nr   r    )r7   s    r   
get_prefix+_get_logger_dict_helper.<locals>.get_prefix   s    2v76C<7r   statsN)named_children
isinstanceLoggerr=   _get_logger_dict_helper)r5   r6   r7   r;   namechildmodule_prefixs          r   rA   rA   |   sz    8 ))+eV$$8=K
6*W45 ,
 ))+5;
6*T1MB ,r   c                 `    [         R                  R                  S5        0 n[        XU5        U$ )a  Traverse the modules and save all logger stats into target dict.
This is mainly used for quantization accuracy debug.

Type of loggers supported:
    ShadowLogger: used to log the outputs of the quantized module and its matching float shadow module,
    OutputLogger: used to log the outputs of the modules

Args:
    mod: module we want to save all logger stats
    prefix: prefix for the current module

Return:
    target_dict: the dictionary used to save all logger stats

z/quantization_api._numeric_suite.get_logger_dict)r)   r*   r+   rA   )r5   r7   r6   s      r   get_logger_dictrF      s,      
HH  !RS#%KCf5r   c                   2   ^  \ rS rSrSrU 4S jrS rSrU =r$ )r@      zBase class for stats loggingc                 Z   > [         TU ]  5         0 U l        [        R                  U l        g N)super__init__r=   r)   quint8dtypeself	__class__s    r   rL   Logger.__init__   s"    
 \\
r   c                     g)	
        Nr:   rP   xs     r   forwardLogger.forward   s    r   )rN   r=   	__name__
__module____qualname____firstlineno____doc__rL   rW   __static_attributes____classcell__rQ   s   @r   r@   r@      s    '" r   r@   c                   2   ^  \ rS rSrSrU 4S jrS rSrU =r$ )ShadowLogger   zVClass used in Shadow module to record the outputs of the original and
shadow modules.
c                 ^   > [         TU ]  5         / U R                  S'   / U R                  S'   g )Nr"   r#   rK   rL   r=   rO   s    r   rL   ShadowLogger.__init__   s*     

7"$

;r   c                    [        U5      S:  a  US   n[        U5      S:  a  US   nU R                  S   R                  UR                  5       5        U R                  S   R                  UR                  5       5        g)rT   r(   r   r#   r"   N)r   r=   appenddetach)rP   rV   ys      r   rW   ShadowLogger.forward   sf    
 q6A:!Aq6A:!A

;&&qxxz2

7""188:.r   r:   rY   ra   s   @r   rc   rc      s    %

/ 
/r   rc   c                   2   ^  \ rS rSrSrU 4S jrS rSrU =r$ )OutputLogger   z+Class used to log the outputs of the modulec                 @   > [         TU ]  5         / U R                  S'   g )N
tensor_valrf   rO   s    r   rL   OutputLogger.__init__   s    #%

< r   c                 B    U R                   S   R                  U5        U$ )rT   rq   )r=   ri   rU   s     r   rW   OutputLogger.forward   s     
 	

< ''*r   r:   rY   ra   s   @r   rn   rn      s    6& r   rn   tc                 l    [        U 5      [        L a  U  Vs/ s H  n[        U5      PM     sn$ U $ s  snf rJ   )typetuple_convert_tuple_to_listru   rV   s     r   ry   ry      s0    59!W5Eq1q!"1%q1L1L1s   1c                     [        U 5      [        L a  U  Vs/ s H  n[        U5      PM     sn$ U R                  (       a  U R	                  5       $ U $ s  snf rJ   )rw   list_dequantize_tensor_listis_quantized
dequantizerz   s     r   r}   r}      sT     7d? .//Q	 	#Q/ >> \\^
 /s   Ac                     ^  \ rS rSrSrU 4S jrS\R                  4S jrS\R                  S\R                  S\R                  4S jr	S\R                  S\
S\R                  4S	 jrS\R                  S\R                  S\R                  4S
 jrS\R                  S\
S\R                  4S jrSS\\R                     S\S\R                  4S jjrS\R                  S\R                  S\R                  4S jrSrU =r$ )Shadow   a  Shadow module attaches the float module to its matching quantized module
as the shadow. Then it uses Logger module to process the outputs of both
modules.

Args:
    q_module: module quantized from float_module that we want to shadow
    float_module: float module used to shadow q_module
    logger_cls: type of logger used to process the outputs of q_module and
        float_module. ShadowLogger or custom loggers can be used.
c                    > [         TU ]  5         Xl        X l        [        R
                  " 5       U l        U" 5       U l        g rJ   )rK   rL   orig_moduleshadow_modulennq
DeQuantizedequantlogger)rP   q_modulefloat_module
logger_clsrQ   s       r   rL   Shadow.__init__   s1    #)~~' lr   r   c                     [        U5      nU R                  " U6 n[        U5      nU R                  " U6 nU R	                  X55        U$ rT   )ry   r   r}   r   r   )rP   rV   xloutputxl_floatshadow_outputs         r   rW   Shadow.forward  sI    
 $A&!!2&*2.**H5F*r   rV   rk   c                     U R                   R                  X5      nUR                  5       nUR                  5       nU R                  R                  X5      nU R	                  X45        U$ r   )r   addr   r   r   rP   rV   rk   r   r   s        r   r   
Shadow.add  W    
 !!%%a+LLNLLN**..q4F*r   c                     U R                   R                  X5      nUR                  5       nU R                  R                  X5      nU R	                  X45        U$ r   )r   
add_scalarr   r   r   r   s        r   r   Shadow.add_scalar  L    
 !!,,Q2LLN**55a;F*r   c                     U R                   R                  X5      nUR                  5       nUR                  5       nU R                  R                  X5      nU R	                  X45        U$ r   )r   mulr   r   r   r   s        r   r   
Shadow.mul*  r   r   c                     U R                   R                  X5      nUR                  5       nU R                  R                  X5      nU R	                  X45        U$ r   )r   
mul_scalarr   r   r   r   s        r   r   Shadow.mul_scalar6  r   r   dimc                     U R                   R                  X5      nU Vs/ s H  oDR                  5       PM     nnU R                  R                  X5      nU R	                  X55        U$ s  snf r   )r   catr   r   r   )rP   rV   r   r   rk   r   s         r   r   
Shadow.catA  s^    
 !!%%a-%&'Q\\^Q'**..q6F* (s   A)c                     U R                   R                  X5      nUR                  5       nUR                  5       nU R                  R                  X5      nU R	                  X45        U$ r   )r   add_relur   r   r   r   s        r   r   Shadow.add_reluL  sW    
 !!**10LLNLLN**33A9F*r   )r   r   r   r   )r   )rZ   r[   r\   r]   r^   rL   r)   TensorrW   r   r"   r   r   r   r|   intr   r   r_   r`   ra   s   @r   r   r      s    	#
U\\ 

U\\ 
ell 
u|| 
	ELL 	U 	u|| 	
U\\ 
ell 
u|| 
	ELL 	U 	u|| 		T%,,' 	c 	%,, 	
%,, 
5<< 
ELL 
 
r   r   r   r   module_swap_listr   c                    [         R                  R                  S5        0 nU R                  5        H	  u  pVXdU'   M     0 nUR                  5        H\  u  pVXT;  a  M  XE   n[	        U5      U;  a  [        XX#5        [	        U5      U;   d  M<  [        Xh5      (       a  MN  [        XhU5      Xu'   M^     UR                  5        H  u  pXR                  U	'   M     g)am  Prepare the model by attaching the float module to its matching quantized
module as the shadow if the float module type is in module_swap_list.

Example usage::

    prepare_model_with_stubs(float_model, q_model, module_swap_list, Logger)
    q_model(data)
    ob_dict = get_logger_dict(q_model)

Args:
    float_module: float module used to generate the q_module
    q_module: module quantized from float_module
    module_swap_list: list of float module types to attach the shadow
    logger_cls: type of logger to be used in shadow module to process the outputs of
        quantized module and its float shadow module
z8quantization_api._numeric_suite.prepare_model_with_stubsN)
r)   r*   r+   r>   rw   prepare_model_with_stubs_is_identical_module_typer   items_modules)r   r   r   r   float_module_childrenrB   r5   reassign	float_modr.   values              r   r   r   Y  s    , 
HH  B !002	&)d# 3 H,,.	,)/		?"22$Y5ER 	?..7P8
 8
 $CJ?HN /  nn&
!&# 'r   c                     U R                  5        Vs/ s H  n[        U5      PM     nnUR                  5        Vs/ s H  n[        U5      PM     nnX4:H  $ s  snf s  snf rJ   )modulesrw   )mod1mod2r5   mod1_module_typesmod2_module_typess        r   r   r     sQ    .2lln=nscn=.2lln=nscn=11 >=s
   AA)r   float_modelq_modelc                |    [         R                  R                  S5        [        XX#5        U" U6   [	        U5      nU$ )aR  Compare quantized module in a model with its floating point counterpart,
feeding both of them the same input. Return a dict with key corresponding to
module names and each entry being a dictionary with two keys 'float' and
'quantized', containing the output tensors of quantized and its matching
float shadow module. This dict can be used to compare and compute the module
level quantization error.

This function first call prepare_model_with_stubs() to swap the quantized
module that we want to compare with the Shadow module, which takes quantized
module, corresponding float module and logger as input, and creates a forward
path inside to make the float module to shadow quantized module sharing the
same input. The logger can be customizable, default logger is ShadowLogger
and it will save the outputs of the quantized module and float module that
can be used to compute the module level quantization error.

Example usage::

    module_swap_list = [torchvision.models.quantization.resnet.QuantizableBasicBlock]
    ob_dict = compare_model_stub(float_model,qmodel,module_swap_list, data)
    for key in ob_dict:
        print(key, compute_error(ob_dict[key]['float'], ob_dict[key]['quantized'].dequantize()))

Args:
    float_model: float model used to generate the q_model
    q_model: model quantized from float_model
    module_swap_list: list of float module types at which shadow modules will
        be attached.
    data: input data used to run the prepared q_model
    logger_cls: type of logger to be used in shadow module to process the outputs of
        quantized module and its float shadow module
z2quantization_api._numeric_suite.compare_model_stub)r)   r*   r+   r   rF   )r   r   r   r   dataob_dicts         r   compare_model_stubr     s9    L 
HH  !UV[3CPTNg&GNr   c                    [         R                  R                  S5        [        U 5      n[        U5      n0 nU HO  n[	        X5   S   5      S:X  a  M  [        [        USS9US5      nUc  M3  0 XE'   X&   S   XE   S'   X5   S   XE   S'   MQ     U$ )	a  Find the matching activation between float and quantized modules.

Args:
    float_module: float module used to generate the q_module
    q_module: module quantized from float_module

Return:
    act_dict: dict with key corresponding to quantized module names and each
    entry being a dictionary with two keys 'float' and 'quantized', containing
    the matching float and quantized activations
z8quantization_api._numeric_suite.get_matching_activationsrq   r   T)reverser=   r"   r#   )r)   r*   r+   rF   r   r   sorted)r   r   r   r   act_dictr.   r/   s          r   get_matching_activationsr     s     
HH  B !.J$X.N "H~"<01Q6z4 @#wO	 HM%/%:<%HHM'")7)<\)JHM+&  Or   c                     [         R                  R                  S5        Uc
  [        5       n[         R                  R
                  R                  USS9nX@l        [        U SU0 S9  XAl        [        USU[        0 S9  g)ai  Prepare the model by attaching the logger to both float module
and quantized module if they are in the allow_list.

Args:
    float_module: float module used to generate the q_module
    q_module: module quantized from float_module
    logger_cls: type of logger to be attached to float_module and q_module
    allow_list: list of module types to attach logger
z5quantization_api._numeric_suite.prepare_model_outputsN)
activationr!   T)inplace
allow_listprepare_custom_config_dict)r   r   observer_non_leaf_module_listr   )
r)   r*   r+   r   aoquantizationQConfigqconfigr   *NON_LEAF_MODULE_TO_ADD_OBSERVER_ALLOW_LIST)r   r   r   r   qconfig_debugs        r   prepare_model_outputsr     s     
HH  ? ;=
HH))11ZPT1UM(dzVX %&P#%r   )r   r   c                    [         R                  R                  S5        Uc
  [        5       n[	        XX#5        U " U6   U" U6   [        X5      nU$ )a  Compare output activations between float and quantized models at
corresponding locations for the same input. Return a dict with key corresponding
to quantized module names and each entry being a dictionary with two keys
'float' and 'quantized', containing the activations of quantized model and
float model at matching locations. This dict can be used to compare and
compute the propagation quantization error.

Example usage::

    act_compare_dict = compare_model_outputs(float_model, qmodel, data)
    for key in act_compare_dict:
        print(
            key,
            compute_error(
                act_compare_dict[key]['float'],
                act_compare_dict[key]['quantized'].dequantize()
            )
        )

Args:
    float_model: float model used to generate the q_model
    q_model: model quantized from float_model
    data: input data used to run the prepared float_model and q_model
    logger_cls: type of logger to be attached to float_module and q_module
    allow_list: list of module types to attach logger

Return:
    act_compare_dict: dict with key corresponding to quantized module names
    and each entry being a dictionary with two keys 'float' and 'quantized',
    containing the matching float and quantized activations
z5quantization_api._numeric_suite.compare_model_outputs)r)   r*   r+   r   r   r   )r   r   r   r   r   act_compare_dicts         r   compare_model_outputsr     sT    L 
HH  ? ;=
+
GTN/Er   )r   )-typingr   r   r   r   r)   torch.ao.nn.quantizedr   nnr#   r   torch.ao.nn.quantized.dynamicdynamicnnqdtorch.nntorch.ao.quantizationr   +torch.ao.quantization.quantization_mappingsr   LinearLSTMr   dictstrr|   r   r   r4   ModulerA   rF   r@   rc   rn   ry   r}   r   setrw   r   r   r   r   r   r   r:   r   r   <module>r      s   1 1  # # , ,  ) 	KKJJIIGG	. *DcNDI-.  c]	BBS#XB04S#XB	#tC%&
&'BP C	Cc3hC C 
	C4 C c4i .RYY $/6 /.6  Mc Mc Ms s bRYY bJ0'))0'ii0' $i0' 	0'
 
0'f2 **YY* $i* 
#t)_*Z))ii 
#tC%&
&'F 	!))!ii!
 
!P //YY/ 
#tC%&
&'/r   