
    Vhh!                        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
 ej                  j                  j                  Zej                  d       dev r 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j,                  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_TSAN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         X/home/dcms/DCMS/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   _requantizer/   +   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   r3   )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_qparamsrG   2   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 )r1   r   )r%   r4   r5   )r:   r6   r;   r<   r   r   r   r   zerosshapefloat64r   ranger=   r>   r?   r   )
rA   r%   r#   r$   n_levelsr!   r"   irD   rE   s
             r   &_calculate_dynamic_per_channel_qparamsrO   [   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      rLt        |       t        |      k(  sJ t	        t        |             D cg c]  }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 c c}w )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   r5   inf   )r:   listtuplelenrL   _snris_quantized
dequantizenormr)   log10)r    x_hatidxresnoisesignalsnrsnr_dbs           r   rV   rV   u   s     !dE]#1vU###38Q=ACtAcFE#J'AA
  "~~LLNYEzE%L%,..VVXF
5.C#))+F5&   Bs   C7c              #   "  K   t         j                  j                  j                  }| t         j                  j                  _        	 d  |t         j                  j                  _        y # |t         j                  j                  _        w xY wwNr6   backends	quantizedengine)qenginepreviouss     r   override_quantized_enginerj      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rc   )r6   _C!_set_default_mobile_cpu_allocator#_unset_default_mobile_cpu_allocator)qengine_is_qnnpacks    r   "override_cpu_allocator_for_qnnpackrp      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rc   )supported_qenginesrj   )argskwargsrh   	qfunctions      r   test_fnz"override_qengines.<locals>.test_fn   sA    ) 	+G*73 +4*6*+ +	++ +s   	*3	 )rv   rw   s   ` r   override_qenginesry      s    +
 Nr   c                  P    t         j                  j                  j                  dk(  S )Nfbgemmrd   rx   r   r   qengine_is_fbgemmr|          >>##**h66r   c                  P    t         j                  j                  j                  dk(  S )Nr	   rd   rx   r   r   ro   ro      s    >>##**i77r   c                  P    t         j                  j                  j                  dk(  S )Nonednnrd   rx   r   r   qengine_is_onednnr      r}   r   c                  P    t         j                  j                  j                  dk(  S )Nx86rd   rx   r   r   qengine_is_x86r      s    >>##**e33r   c                     t        t        | j                                     }d||<   ||d<   | j                  t	        |            }||fS )Nr   )rS   rL   dimpermuterT   )rA   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   r4   )r%   r   tor6   r>   
zeros_likerL   sizeclampr   r   rT   )rA   per_channel_scaleper_channel_zero_pointr   	quant_min	quant_maxr%   permute_axis_listr]   rN   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   r6   r>   r   rL   r   r   r   rT   )dYrA   r   r   r   r   r   r%   r   XqrN   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:   r6   r;   tensordetachcloner   r   r>   )rA   r   s     r   	to_tensorr      sQ    a&LLOHHJ44u||F+5==4AAr   )r   )%__doc__r<   r   r6   
contextlibr   $torch.testing._internal.common_utilsr   r   r   r   re   rf   supported_enginesrs   removeanyr   uint8r'   r*   r/   r7   rG   rO   rV   rj   rp   ry   r|   ro   r   r   r   r   r   r   rx   r   r   <module>r      s     % ] ]^^--??    & ! ""sFNHj+Y'Zi( '(J *.D 	 12288  7<UE\E\ '+R4!6 3 3 ; ;7874

Br   