
    rh1E                     H   d Z ddlZddlZddlm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%de&de&fdZ'd\  Z(Z) e'e(d z
        Z*d!ed"e&d#e&defd$Z+d!ed"e&d#e&defd%Z,d& Z-dej                  fd'Z.y))z`Importing this file includes common utility methods for checking quantized
tensors and modules.
    N)Tensor)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         {/var/www/html/ai-insurance-compliance-backend/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   _requantizer0   ,   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   r4   )r   r,         ?r           )torchper_tensor_affineper_tensor_symmetricqint8
isinstancer   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   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 )r2   r   r&   r5   r6   )r;   r7   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_qparamsrP   \   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   r6   inf   )r;   listtuplelenrM   _snris_quantized
dequantizenormr*   log10)r!   x_hatidxresnoisesignalsnrsnr_dbs           r   rW   rW   v   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r7   backends	quantizedengine)qenginepreviouss     r   override_quantized_enginerk      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rd   )r7   _C!_set_default_mobile_cpu_allocator#_unset_default_mobile_cpu_allocator)qengine_is_qnnpacks    r   "override_cpu_allocator_for_qnnpackrq      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rd   )supported_qenginesrk   )argskwargsri   	qfunctions      r   test_fnz"override_qengines.<locals>.test_fn   sA    ) 	+G*73 +4*6*+ +	++ +s   	*3	 )rw   rx   s   ` r   override_qenginesrz      s    +
 Nr   c                  P    t         j                  j                  j                  dk(  S )Nfbgemmre   ry   r   r   qengine_is_fbgemmr}          >>##**h66r   c                  P    t         j                  j                  j                  dk(  S )Nr
   re   ry   r   r   rp   rp      s    >>##**i77r   c                  P    t         j                  j                  j                  dk(  S )Nonednnre   ry   r   r   qengine_is_onednnr      r~   r   c                  P    t         j                  j                  j                  dk(  S )Nx86re   ry   r   r   qengine_is_x86r      s    >>##**e33r   c                     t        t        | j                                     }d||<   ||d<   | j                  t	        |            }||fS )Nr   )rT   rM   dimpermuterU   )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   r5   )r&   r   tor7   r>   
zeros_likerM   sizeclampr   r   rU   )rA   per_channel_scaleper_channel_zero_pointr   	quant_min	quant_maxr&   permute_axis_listr^   rO   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   r7   r>   r   rM   r   r   r   rU   )dYrA   r   r   r   r   r   r&   r   XqrO   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;   r7   r   tensordetachcloner   r   r>   )rA   r   s     r   	to_tensorr      sQ    a&LLOHHJ44u||F+5==4AAr   nreturnc                     d| z  dz
  S Nr   ry   )r   s    r   _n_onesr      s    Fa<r   )      r   r!   ebitsmbitsc                    | j                   t        j                  k(  sJ d|z   |z   dk  sJ t        |dz
        }t        ||z         }d||z   z  }t        t        |z
  dz
        }dt        |      |z
  z  t        |dz         d|z  z  z  }dd|z
  z  }t
        |z
  t        |z
  z   dz   }	|	t        z  }
t        j                  |
t        j                        j                  t        j                        }| j                  t        j                        } | dz  }| |z  } | j                  t        j                        } | |k\  }t        j                  t        j                  |      | |k        }t        j                  t        j                  ||            }| |z   }|j                  t        j                        }||
z  }|j                  t        j                        }| j                  t        j                        }|t        |z
  z	  dz  }|t
        z
  t        z  |z   }||z  }||z  }|t        |z
  z	  }|j                  t        j                        }t        j                  | |t        j                        } t        j                   |||       } t        j                   |||       } |t        t"        z   |z
  |z
  z	  }|j                  t        j                        }||z  }| |z  } | j                  t        j                        S )aJ  Convert FP32 numbers to sub-byte floating point numbers with the given
    number of exponent and mantissa bits.

    Input: torch.Tensor of dtype torch.float
    Output: torch.Tensor of dtype torch.uint8, where the bit encoding is stored
    in the least significant bits. e.g.
      fp4: bits 0-3 empty and bits 4-7 in fp4_e2m1 encoding
      fp6: bits 0-1 empty and bits 2-7 in fp6_e2m3 or fp6_e3m2 encoding

    Note: there are no special values (NaN, inf) support in this code. Values
    outside the representable range of Floatx after rounding are clamped to the
    maximum Floatx magnitude (sign is preserved).

    Code below is an adaptation of https://fburl.com/code/ciwofcg4

    Background 1: last answer in https://stackoverflow.com/q/8981913
    Background 2: Computer Organization and Design, RISC-V edition, Chapter 3.5
    r   r   r   rI   l        )r&   r7   r*   r   	MBITS_F32F32_EXP_BIASr   int32viewr>   logical_andlogical_not
logical_orr   uint8	full_likewhere	EBITS_F32)r!   r   r   exp_biasmax_int	sign_maskmagic_adder
max_normal
min_normal
denorm_expdenorm_mask_intdenorm_mask_floatsignsaturate_maskdenormal_masknormal_mask
denormal_xnormal_xmant_odd
val_to_addsign_lps                        r   _f32_to_floatx_unpackedr      s   & 77ekk!!!u9u!!! uqy!Heem$Geem$I )e+a/0K wu~01WUQY5G1e85TUJ q8|$J 
	 u	 		  !I-O _EKKHMM 	
u{{Az>D 	
DA 	
u{{A OM%%e&7&7&FJWM##E$4$4]M$RSK &&J-J/!Ju{{+J
 vvekk"HY./14Hl*y8KGJ
HHI-.H{{5;;'H
 	7%++6AM:q1AK1-A y9,u4u<=Gjj%G
 	!G	GA44r   c                    | j                   t        j                  k(  sJ d|z   |z   dk  sJ d||z   z  }t        |dz
        }t        |      }| |z  }| |z  }|dk(  }t        j                  |dkD  ||z	  dk(        }	||z	  }
|
|z
  t
        z   }|j                  t        j                        t        z  }||z  j                  t        j                        }|t        |z
  z  }||z  }d||<   d|z
  t
        z   }|dk(  r||z
  t        z  ||	<   nrt        |      D ]M  }t        d|z  d|dz   z        D ]3  }||z
  }|d|z  z
  |t        z   |z
  z  }||z
  t        z  }||z   |||k(  <   5 O t        j                  |	||      }|j                  t        j                        t        |z
  t        z   |z
  z  }||z  }|j                  t        j                        S )a  Convert sub-byte floating point numbers with the given number of exponent
    and mantissa bits to FP32.

    Input: torch.Tensor of dtype uint8, where the bit encoding is stored
    in the least significant bits. e.g.
      fp4: bits 0-3 empty and bits 4-7 in fp4_e2m1 encoding
      fp6: bits 0-1 empty and bits 2-7 in fp6_e2m3 or fp6_e3m2 encoding
    Output: torch.Tensor of dtype fp32 with the dequantized value
    r   r   r   )r&   r7   r   r   r   r   r   r   r   rM   r   r   r   r*   )r!   r   r   r   r   mantissa_maskr   x_pos	zero_maskr   exp_biased_lpexp_biased_f32mantissa_lp_int32mantissa_f32resultdenormal_exp_biasedrO   mantissa_cmp
left_shiftsign_f32s                       r   _floatx_unpacked_to_f32r   e  s    77ekk!!!u9u!!!eem$Iuqy!HENM )mG KE
 
I
 %%uqyUe^4IKM UNM"X-<N#&&u{{3y@N .225;;?$U):;Ll*F
 F9h,5 z!4u!< J} u 	A %a1faAEl ;  #QY
 ,Q 7*U2  #6
"By!P #\1 ""3|"CD	" ],=vF zz%++&9u+<y+H5+PQHhF;;u{{##r   c                     | |z   dz
  |z  S r   ry   )abs     r   ceil_divr     s    EAI!r   c                    | j                   \  }}t        |d      }t        |d      }|dz  }|dz  }| }||f||fk7  r9t        j                  ||f| j                  | j
                        }| |d|d|f<   |j                  |d|d      j                  dddd      }|j                  d	dd
d      j                  dd      j                  d	d
d      }	|	j                         S )a[  
    Rearrange a large matrix by breaking it into blocks and applying the rearrangement pattern.

    See:
        https://docs.nvidia.com/cuda/cublas/index.html#d-block-scaling-factors-layout

    Args:
        input_matrix: Input tensor of shape (H, W)

    Returns:
        Rearranged tensor of shape (32*ceil_div(H,128), 16*ceil_div(W,4))
          r   Nr   r   r             )rK   r   r7   rJ   r   r&   r   r   reshape	transposeflatten)
input_matrixrowscolsn_row_blocksn_col_blockspadded_rowspadded_colspaddedblocks
rearrangeds
             r   
to_blockedr     s     ##JD$D#&LD!$L $K"KFd|[11k;7@S@S[g[m[mn+uuete| [[sL!<DDQ1aPFAr1-771=EEb"bQJr   )r   )/__doc__r<   r   r7   r   
contextlibr   $torch.testing._internal.common_utilsr   r   r   r   rf   rg   supported_enginesrt   removeanyr   r   r(   r+   r0   r8   rG   rP   rW   rk   rq   rz   r}   rp   r   r   r   r   r   r   r@   r   r   r   r   r   r   r   r   ry   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s s   	9y1}%sv sc s# s& spX$v X$c X$# X$& X$v   r   