
    sg!                        d Z ddlZddlZddlmZ ddlmZmZm	Z	m
Z
mZmZ ej                  j                  j                  Zej#                  d       dev r ee
eee	eeg      rej#                  d       	 ddZddej(                  fdZd	 Zdd
ej(                  fdZdej0                  fdZd Zd Zed        Zed        Zd Zd Zd Z d Z!d Z"d Z#d Z$d Z%d Z&y)z`Importing this file includes common utility methods for checking quantized
tensors and modules.
    N)contextmanager)TEST_WITH_ASANTEST_WITH_TSANTEST_WITH_UBSANIS_PPCIS_MACOS
IS_WINDOWSnoneqnnpackc                 n    t        j                  | d|z  z   |z
  |dz
  |dz
  z  z
  |z        d|z  z   dz   S )z7Computes the output shape given convolution parameters.      )npfloor)
input_sizekernel_sizepaddingstridedilationoutput_paddings         [/var/www/html/venv/lib/python3.12/site-packages/torch/testing/_internal/common_quantized.py_conv_output_shaper      s\     88Z!g+-;{Q 1?& &)/0 134~3EFHIJ J    c                 J   |t        j                  |      j                  }|t        j                  |      j                  }t        j                  | |z  |z         j                  t         j                        }t        j                  |||      }|j                  |      }|S )zQuantizes a numpy array.)r   iinfominmaxroundastypeint64clip)xscale
zero_pointqminqmaxdtypeqxs          r   	_quantizer)      s}    |xx""|xx""	!e)j(	)	0	0	:B	T4	 B	5	BIr   c                 <    | j                  t              |z
  |z  }|S )zDequantizes a numpy array.)r   float)r(   r#   r$   r"   s       r   _dequantizer,   &   s    	5	J	&%/AHr      c                 ~    | |z  j                         |z   }t        j                  |||      j                  |      }|S )zhRequantizes a numpy array, i.e., intermediate int32 or int16 values are
    converted back to given type)r   r   r!   r   )r"   
multiplierr$   r%   r&   qtyper(   s          r   _requantizer1   ,   s=     j.			!J	.B	T4	 	'	'	.BIr   Fc                    |t         j                  t         j                  fv sJ |t         j                  k(  r|t         j                  k(  sJ t	        | t         j
                        r| j                         } |t         j                  k(  r|rd\  }}nd\  }}n|rd\  }}nd\  }}| j                         }| j                         }|t         j                  k(  }||k(  rd}	d}
n|rUt        ||       }| }||z
  ||z
  z  }	t        |	t        j                  t        j                        j                        }	d}
nt        |d      }t        |d      }||z
  ||z
  z  }	t        |	t        j                  t        j                        j                        }	|t        ||	z        z
  }
t        ||
      }
t        ||
      }
t        |	      t        |
      gS )xCalculate the dynamic quantization parameters (scale, zero_point)
    according to the min and max element of the tensor)i?   )i   )r   r5   )r   r-         ?r           )torchper_tensor_affineper_tensor_symmetricqint8
isinstanceTensornumpyr   r   r   finfofloat32epsr   r+   int)Xr'   reduce_rangeqschemer%   r&   min_valmax_valis_symmetricr#   r$   s              r   _calculate_dynamic_qparamsrI   3   s    u..0J0JKKKK%,,,###!U\\"GGI JD$"JD$JD$JD$eegGeegGu999L'
'G8,GhGw&4$;7Erxx

3778EJ'3'G'3'Gw&4$;7Erxx

3778Ego 66JT:.JT:.J%L#j/**r   c                 |   t        | t        j                        r| j                         } t        j                  |      j
                  t        j                  |      j                  }}||z
  }t        j                  | j                  d   t        j                        }t        j                  | j                  d   t        j                        }t        |j                  d         D ]  }| j                         }| j                         }	||	k(  rd||<   d||<   3t        |	d      }	t        |d      }|	|z
  |z  ||<   t        ||   t        j                  t        j                        j                        ||<   |t!        |||   z        z
  ||<   t        |||         ||<   t        |||         ||<    ||fS )r3   r   )r'   r6   r7   )r<   r8   r=   r>   r   r   r   r   zerosshapefloat64r    ranger?   r@   rA   r   )
rC   r'   r%   r&   n_levelsr#   r$   irF   rG   s
             r   &_calculate_dynamic_per_channel_qparamsrQ   \   sw    !U\\"GGIU#''U);)?)?$Dd{HHHQWWQZrzz2E!''!*BHH5J:##A&' 5%%'%%'gE!HJqM'3'G'3'G')X5E!H58RXXbjj%9%=%=>E!H 558);#<<JqMjm4JqMjm4JqM5 *r   c                    t        | t        t        f      rWt        |       t        |      k(  sJ g }t	        t        |             D ]#  }|j                  t        | |   ||                % |S |j                  r|j                         }| j                  r| j                         } | |z
  j                         }|dk(  rdt        d      t        d      fS | j                         }||z  }d|j                         z  }|||fS )a  Calculates the signal to noise ratio and returns the signal and noise
    power, as well as the SNR in dB.
    If the input is a list/tuple this function is called recursively on each
    element. The result will have the same nested structure as the inputs.

    Args:
        x, x_hat: Either a tensor or a nested list/tuple of tensors.
    Returns:
        signal, noise, SNR(in dB): Either floats or a nested list of floats
    r   r7   inf   )r<   listtuplelenrN   append_snris_quantized
dequantizenormr+   log10)r"   x_hatresidxnoisesignalsnrsnr_dbs           r   rY   rY   v   s     !dE]#1vU###Q= 	1CJJtAcFE#J/0	1
  "~~LLNYEzE%L%,..VVXF
5.C#))+F5&  r   c              #   "  K   t         j                  j                  j                  }| t         j                  j                  _        	 d  |t         j                  j                  _        y # |t         j                  j                  _        w xY wwNr8   backends	quantizedengine)qenginepreviouss     r   override_quantized_enginerm      sY     ~~''..H&-ENN#3*2  '(  's   ABA+  B+!BBc              #      K   	 | rt         j                  j                          d  | rt         j                  j                          y y # | rt         j                  j                          w w xY wwrf   )r8   _C!_set_default_mobile_cpu_allocator#_unset_default_mobile_cpu_allocator)qengine_is_qnnpacks    r   "override_cpu_allocator_for_qnnpackrs      sR     ;HH668HH88: HH88: s   A0$A
 "A0
#A--A0c                       fd}|S )Nc                  l    t         D ]  }t        |      5   | i | d d d          y # 1 sw Y   +xY wrf   )supported_qenginesrm   )argskwargsrk   	qfunctions      r   test_fnz"override_qengines.<locals>.test_fn   sA    ) 	+G*73 +4*6*+ +	++ +s   	*3	 )ry   rz   s   ` r   override_qenginesr|      s    +
 Nr   c                  P    t         j                  j                  j                  dk(  S )Nfbgemmrg   r{   r   r   qengine_is_fbgemmr          >>##**h66r   c                  P    t         j                  j                  j                  dk(  S )Nr   rg   r{   r   r   rr   rr      s    >>##**i77r   c                  P    t         j                  j                  j                  dk(  S )Nonednnrg   r{   r   r   qengine_is_onednnr      r   r   c                  P    t         j                  j                  j                  dk(  S )Nx86rg   r{   r   r   qengine_is_x86r      s    >>##**e33r   c                     t        t        | j                                     }d||<   ||d<   | j                  t	        |            }||fS )Nr   )rU   rN   dimpermuterV   )rC   axisnew_axis_listys       r   _permute_to_axis_zeror      sH    quuw(MM$M!			%&'Amr   c           	         | j                   }t        | j                  t        j                        |      \  } }t        j
                  |       }t        | j                         d         D ]M  }	t        j                  t        j                  | |	   d||	   z  z  ||	   z         ||      ||	   z
  ||	   z  ||	<   O |j                  t        |            }
|
j                  |      S Nr   r6   )r'   r   tor8   r@   
zeros_likerN   sizeclampr   r   rV   )rC   per_channel_scaleper_channel_zero_pointr   	quant_min	quant_maxr'   permute_axis_listr_   rP   outs              r   +_fake_quantize_per_channel_affine_referencer      s    GGE0emm1DdKA


1
C1668A; x++ekk!A$#8I!8L2L*M(++, -.7DF\]^F_`ctuvcwxAx ++e-.
/C66%=r   c                    |j                   }t        |j                  t        j                        |      \  }}t        j
                  |      }	t        |j                         d         D ],  }
t        j                  ||
   d||
   z  z  ||
   z         |	|
<   . |	j                  t        |            }	|	|k\  |	|k  z  }t        j
                  |       }| |   ||<   |j                  |      S r   )r'   r   r   r8   r@   r   rN   r   r   r   rV   )dYrC   r   r   r   r   r   r'   r   XqrP   maskr_   s                r   0_fake_quantize_per_channel_affine_grad_referencer      s    GGE0emm1DdKA			!	B1668A; ]AaDC*;A*>$>?BXYZB[[\1]	E+,	-B)Oi0D


2
C4CI66%=r   c                    t        | t        j                        st        j                  |       } n| j	                         j                         } | j                  t        j                  |      t        j                        S )N)devicer'   )	r<   r8   r=   tensorclonedetachr   r   r@   )rC   r   s     r   	to_tensorr      sQ    a&LLOGGI44u||F+5==4AAr   )r   )'__doc__r>   r   r8   
contextlibr   $torch.testing._internal.common_utilsr   r   r   r   r   r	   rh   ri   supported_enginesrv   removeanyr   uint8r)   r,   r1   r9   rI   rQ   rY   rm   rs   r|   r   rr   r   r   r   r   r   r   r{   r   r   <module>r      s     % ~ ~^^--??    & ! ""sFNNTcemoy+z'{i( '(J *.D 	 12288  7<UE\E\ '+R4!: 3 3 ; ;7874

Br   