
    ybjh                        S r SSKJr  SSKrSSKrSSKJr  SSKr\R                  " \
5      r\(       a  SSKrS rS rSS jr\R                   " SS	9SS
 j5       rS rSS jrSSS jjrS r " S S5      rg)aw  CUDA weight-only quantization helpers.

This module contains small Python utilities for producing the weight layouts
consumed by CUDA weight-only kernels. The blockwise quantizers wrap the same C++
pybind entry points used by runtime prepacking, and the mixed-GEMM weight packer
is a PyTorch reimplementation of the runtime CUDA packing, so tests and model
builders can generate byte-identical quantized weights. The PyTorch packer runs
on CUDA when a device is available and falls back to CPU otherwise, which is the
only option on platforms where the standalone CUDA packer is not built (Windows).
A GPU-gated parity test validates it against that standalone CUDA packer.

Two storage families are exposed:

* raw MatMulNBits blockwise storage, laid out by output channel as ``[N, K/pack]``;
* CUDA mixed-GEMM prepacked storage. MatMulNBits prepacked initializers keep the
    schema shape ``[N, K/block_size, block_size*bits/8]`` and require the node
    attribute ``weight_prepacked=1``. QMoE/CUTLASS callers use the kernel-facing
    shape ``[K, N/pack]``.

All public helpers take one logical expert weight matrix with shape ``[N, K]``.
    )annotationsN)TYPE_CHECKINGc                 L     SSK n U $ ! [         a  n[        S5      UeSnAff = f)zQImport torch lazily so importing onnxruntime.quantization does not require torch.r   NzMCUDA weight-only quantization requires torch. Please install torch to use it.)torchImportError)r   es     ڣ/tmp/claude-0/-home-danvics-docker-quiz/c1e0577a-e42c-4a3d-b1ea-3edd61103a4e/scratchpad/stt/lib/python3.13/site-packages/onnxruntime/quantization/cuda_quantizer.py
_get_torchr
   +   s5    r L  rijpqqrs    
##c                      SSK Jn    U R                  $ ! [         a  n[        S5      UeSnAff = f! [         a  n[        S5      UeSnAff = f)a  Return the standalone CUDA mixed-GEMM weight packer (parity oracle).

Production packing uses the PyTorch implementation (``_pack_weights_for_cuda_mixed_gemm``).
This standalone packer lives in ``onnxruntime.capi.onnxruntime_cuda_quant_preprocess``, a
separate extension module that links the CUDA runtime (built only on non-Windows CUDA
builds). It is imported lazily here (never at ``import onnxruntime`` time) and is used by
the parity test to validate the PyTorch packer byte-for-byte.
r   )!onnxruntime_cuda_quant_preprocesszThe standalone CUDA weight packer (onnxruntime_cuda_quant_preprocess) is unavailable; it is built only on non-Windows onnxruntime-gpu CUDA builds.NzNonnxruntime_cuda_quant_preprocess is missing pack_weights_for_cuda_mixed_gemm.)onnxruntime.capir   r    pack_weights_for_cuda_mixed_gemmAttributeError)_cuda_quantr   s     r	   %_get_pack_weights_for_cuda_mixed_gemmr   5   sh    Us;;;  K
 	  sjkqrrss$    3 
0+0
AA		Ac                 :     [        5         g! [         a     gf = f)a  Return True if mixed-GEMM weight prepacking is available.

Prepacking is implemented with PyTorch (CUDA when available, CPU otherwise), so it is
available whenever torch is importable. Callers use this to skip prepack code paths
(and tests) when torch is unavailable.
FT)r
   r        r	   has_cuda_weight_prepackingr   L   s%       s   
 
   )maxsizec                 .    [         R                  S5        g )NzCUDA device is not available; packing mixed-GEMM weights on CPU with PyTorch. This is correct but significantly slower for large Mixture-of-Experts models. Pack on a CUDA-enabled machine for best performance.)_loggerwarningr   r   r	   _warn_cpu_prepack_oncer   Z   s    OO	?r   c                     [        5       n U R                  R                  5       (       a  U R                  " S5      $ [	        5         U R                  " S5      $ )zRPick the torch device for mixed-GEMM weight packing (CUDA if available, else CPU).cudacpu)r
   r   is_availabledevicer   )r   s    r	   _prepack_devicer!   c   s@    LEzz  ||F##<<r   c                F	   [        5       nSnUS:X  a  SOSnU R                  5       S:X  a  U R                  S5      n / SQ/ SQS.nSnS	U-  nU R                  S   U R                  S
   U R                  S   pn	X-  S:w  d  X-  S:w  a  [	        SU
 SU SU SU S3	5      eUS:  a=  Xd SU 3   n[        U
5       Vs/ s H  oU-  U-  XU-     -   PM     nnU SS2USS24   n U R                  nUS:X  a  U R                  UR                  5      nUS-	  R                  SSS
5      R                  S5      nUS-  S-	  R                  SSS
5      R                  S5      nUR                  " UU/SS9R                  UR                  S   SUR                  S
   5      nUSS2SS2SSS24   USS2SS2S
SS24   S-  -   nUR                  UR                  5      R                  U5      n O"U R                  SSS
5      R                  U5      n XE-  nUS
:  as  US:  am  SU-  nSU-  nU
U-  S:w  d	  U
U-  S:w  a  [	        SU
 S35      eU R                  U	SUU
U-  US-  U-  5      n U R                  SS
SSS5      R                  U5      n US:X  a  U R                  UR                  5      nUSUS:  R                  UR                  5      -  S	-   -  nUR                  SS5      SS2/ SQ4   R                  U5      nUR                  UR                  5      R                  UR                  5      n GOPU R                  UR                  5      nUS-	  R                  S5      nUS-  S-	  R                  S5      nUR                  " UU/SS9R                  UR                  S   UR                  S
   S5      nUR                  SS5      SS2/ SQ4   R                  UR                  5      nUR                  UR                  5      nUSUS :  R                  UR                  5      -  S-   -  nUSS2SS2SSS24   USS2SS2S
SS24   S-  -   nUR                  UR                  5      R                  UR                  5      n U R                  S5      R!                  5       $ s  snf )!a  PyTorch port of the runtime CUDA ``preprocess_weights_for_mixed_gemm``.

``tensor`` is a signed int8 weight in ``(K, N/pack)`` packed row-major layout on any
device. Returns the CUTLASS mixed-GEMM layout with the same shape/dtype/device. This
mirrors ``preprocess_weights_for_mixed_gemm_cuda`` (permute_B_rows -> subbyte_transpose
-> interleave_column_major -> add_bias_and_interleave) so its output is byte-identical
to the standalone CUDA packer, for both the SM80 (Ampere) and SM90 (Hopper) layouts.
            r   )r   r   r%   	   r&      
      r$                        ) r   r   r%   r'   r#            r&   r(   r)   r*               r$   r+   r,   r-               r.   r/   r0   r1               )16_816_4   r   zweight shape (rows=z, packed_cols=zF) is incompatible with mixed-GEMM packing (rows must be a multiple of z, packed cols a multiple of z).d   _NdimZ   i       z
num_rows (z0) is incompatible with column-interleave tiling.r(   i    )r   r&   r   r(   )r   r&   r$   r.   r   r(   r+   r/   ir/   )r
   rG   	unsqueezeshape
ValueErrorrangeviewuint8permutecatreshapeint8toint64int16squeeze
contiguous)tensorbitssmr   bits_abits_bpermutation_mapmma_shape_nb_rows_per_mmanum_expertsnum_rowsnum_colspmaprrow_idxoriginal_shapeuhighlowmerged
interleaverows_per_tileelts_in_int32ts                           r	   (_preprocess_weights_for_mixed_gemm_torchrr   l   s    LEF!)QFzz|q!!!$ G!
$OJ Kv%N&,ll1ov||AUV8K A%)?1)D!(>( D33A2BB^_j^kkmo
 	
 
Cx6(34^cdl^mn^mYZ'>9D^AS<TT^mn7A& \\N{KK$Q1a(2215Q1}%%aA.88;C;A.66qwwqz2qwwqzR1add
#fQ14a4Z&82&==UZZ(00@1a(00@ !JA~"r'6)fm#q(H},D,Iz(3cdeeZ])BMTUDUYfDf
 1aA.66~F {IIekk"	TQWLL--33IIb!Q_-55nEekk"''

3KK$Q!!"%Q1}''+C;B/77
AGGAJPRSA&q*B'BCKKFLLY5;;'#!44q881add
#fQ14a4Z&82&==5;;',,UZZ8>>!''))Y os   <Rc                   [        5       n[        U5      n[        U5      nUS;  a  [        SU S35      eUS;  a  [        SU S35      eSU-  n[        5       nUR                  " [
        R                  " U 5      5      R                  UR                  5      R                  XU-  5      R                  U5      nUS:X  a  US-  R                  UR                  5      n	US-	  R                  UR                  5      n
UR                  " X4UR                  US	9nXS
S
2SS
S24'   XS
S
2SS
S24'   US-
  R                  SS5      R                  5       nUS
S
2SS
S24   S-  US
S
2SS
S24   S-  S-  -  R                  UR                  5      R                  UR                  5      nOpUR                  UR                  5      S-
  R                  SS5      R                  5       nUR                  UR                  5      R                  UR                  5      n[!        UR                  5       X45      nUR                  S5      R#                  5       R%                  5       $ )aA  PyTorch implementation of the CUDA ``pack_weights_for_cuda_mixed_gemm``.

``q_weights`` is ORT's unsigned MatMulNBits/QMoE storage ``(N, K/pack)`` (uint8). Returns
a flat ``int8`` numpy array with the CUTLASS mixed-GEMM layout, byte-identical to the
standalone CUDA packer. Runs on CUDA when available, otherwise on CPU.
r$   r%   zbits must be 4 or 8, got .P   rI   z/force_arch must be 80 (SM80) or 90 (SM90), got r%   r$   r1   dtyper    Nr   r&   r   rC   rH   )r
   intrN   r!   	as_tensornpascontiguousarrayrP   rQ   rT   rV   rX   empty	transposerZ   rU   rr   r   numpy)	q_weightsnkr\   
force_archr   packr    qrl   rk   unpackedsigned_tpacked_touts                  r	   !_pack_weights_for_cuda_mixed_gemmr      s    LEt9DZJ64TF!<==!J:,VWXYY9DF,,Y78==ekkJRRST[_V_`ccdjkA qy4xmmEKK(Q{{5;;';;vU[[HADqD ADqDqL++Aq1<<>aAg&-8Aqt!tG3Dt3KPQ2QRVVW\WbWbchhinisistDD%+66q!<GGI;;u{{+00<
283F3F3H$
[C;;r? &&((r   c                 V     SSK Jn Jn  X4$ ! [         a  n[        S5      UeSnAff = f)zCReturn MatMulNBits blockwise quantizers from the ORT pybind module.r   )quantize_matmul_4bitsquantize_matmul_8bitszfCUDA blockwise quantization requires quantize_matmul_4bits and quantize_matmul_8bits from onnxruntime.N)onnxruntime.capi._pybind_stater   r   r   )r   r   r   s      r	   _get_quantize_matmul_nbitsr     s<    	
 !77  t
	s    
(#(c                     \ rS rSrSr\SS.       SS jj5       r\ SSS.           SS jjj5       r\              SS j5       r\SSSSSS	.                 SS
 jj5       r	\ SSSSSS.                 SS jjj5       r
\ SSSSSS.                 SS jjj5       r\SS.         SS jj5       rSrg)CudaQuantizeri  zCUDA quantizer utilities for MoE/QMoE and MatMulNBits-style weight-only kernels.

The methods are stateless; callers may use the class directly without
constructing an object.
Tunsigned_full_rangec                  [        5       nU R                  5       R                  5       R                  UR                  5      R                  5       n [        U5      nUS;  a  [        SU S35      eU R                  u  pESU-  nXV-  S:w  a  [        SU SU S35      eUS	:X  a  U(       a  S
u  pxpOSu  pxpOU(       a  Su  pxpOSu  pxpU R                  5       R                  SSS9[        U	5      -  nUR                  " XR                  " UR                  5      R                  S9nUR                  " UR                  " X-  5      Xx5      R                  UR                   5      R                  5       nX-   R                  UR"                  5      nUS	:X  a>  USS2SSS24   S-  USS2SSS24   S-  S	-  -  nUR                  UR"                  5      nOUnUR                  5       UR%                  S5      R                  5       4$ )a  Quantize one QMoE expert with symmetric per-channel storage.

``weights`` has logical shape ``[N, K]``. Returns raw QMoE storage
``[N, K/pack]`` and scales ``[N]``. By default, this emits the ORT CUDA
QMoE storage contract: unsigned bytes/nibbles with an implicit zero-point
offset, so each stored value is ``q + zero_point`` even though the numeric
quantization is symmetric. By default it uses the full ``[-8, 7]`` /
``[-128, 127]`` range. Set ``unsigned_full_range=False`` to use the legacy
``[-7, 7]`` / ``[-127, 127]`` range.
rt   z=QMoE per-channel quantization only supports 4 or 8 bits, got ru   r%   r   K () must be divisible by z# for QMoE per-channel quantization.r$   r/   r%   r%   r/   r/   r%   rK   rC   rC   rK   rK   rC   r   T)rG   keepdimminNr&   r1   rH   )r
   detachr   rV   float32rZ   rz   rN   rM   absamaxfloatclampfinfoepsroundrX   rQ   rY   )weightsr\   r   r   r   r   r   qminqmaxscale_divisor
zero_pointscales	quantizedqweights                 r	   #qmoe_symmetric_per_channel_quantize1CudaQuantizer.qmoe_symmetric_per_channel_quantize  s   " .."&&(++EMM:EEG4yv\]a\bbcdee}}Dy8q=s1#%<TFBefgg19"8C5M:8C5M:"8K5M:8K5M##4#85;OOVU]])C)G)GHKKG,< =tJMMekkZeeg	+//<	19 ADqD)C/Yq!$Q$w5G#5MRS4STGjj-GG!!#V^^B%7%B%B%DDDr   c                  [        5       n[        R                  U UUS9u  pgU(       d  Xg4$ U R                  u  pS[	        U5      -  n
X-  S:w  a  [        SU SU
 S35      e[        UR                  5       X[	        U5      U5      n[        R                  " U5      R                  [        R                  5      R                  XU
-  5      nUR                  " [        R                  " U5      5      U4$ )a  Quantize per-channel QMoE weights and optionally CUTLASS-prepack them.

When ``prepack`` is true, returned weights have shape ``[K, N/pack]``.
Otherwise, returned weights keep raw per-channel storage ``[N, K/pack]``.
Prepacking uses PyTorch (CUDA when available, CPU otherwise).
r   r%   r   N (r   z! for CUDA QMoE prepacked weights.)r
   r   r   rM   rz   rN   r   r   r|   asarrayrP   rQ   rT   
from_numpyr}   )r   r\   prepackr   r   r   r   r   r   r   r   packeds               r	   qmoe_per_channel_quantize'CudaQuantizer.qmoe_per_channel_quantizeK  s     'KK 3 L 

 ?"}}CI~8q=s1#%<TFBcdee27==?A#d)U_`F#((2::14iH 4 4V <=vEEr   c                  [        5       n[        U5      n[        U5      nU R                  5       R                  5       R	                  UR
                  5      R                  5       R                  5       nUR                  u  pUS;  a  [        SU S35      eUS::  a  [        SU S35      eX-   S-
  U-  n
SU-  nX+-   S-
  U-  nU(       Ga  US:X  a  U(       a  S	OS
u  pnnOU(       a  SOSu  pnnX-  nUU	:w  a  [        R                  " USSUU	-
  44S5      nUR                  XU5      n[        R                  " [        R                  " U5      SS9R                  [        R
                  5      [        R
                  " U5      -  n[        R                   " U[        R"                  " [        R
                  5      R$                  5      n[        R&                  " [        R(                  " UUSS2SS2[        R*                  4   -  5      X5      R                  [        R,                  5      nUU-   R                  [        R.                  5      nUS:X  a  [        R0                  " XU4[        R.                  S9nUSS2SS2SSS24   S-  USS2SS2SUSS2SS2SSS24   R                  S   24'   USS2SS2SUSS2SS2SSS24   R                  S   24==   USS2SS2SSS24   S-  S-  -  ss'   OUn[        R0                  " XS:X  a  U
S-   S-  OU
4[        R.                  S9nUR2                  " U5      UR2                  " U5      UR2                  " U5      4$ [        R4                  " UR6                  5      n[        R0                  " XU4[        R.                  S9n[        R0                  " X4[        R
                  S9n[        R0                  " XS:X  a  U
S-   S-  OU
4[        R.                  S9n[9        5       u  nnUS:X  a  UOUnU" UUUUX(X5        U(       a  [        R                  " U5      nUR2                  " U5      UR2                  " U5      UR2                  " U5      4$ )zMQuantize ``weights`` with MatMulNBits pybinds and return unflattened storage.rt   z6Blockwise quantization only supports 4 or 8 bits, got ru   r   z;Blockwise quantization requires a positive block_size, got r   r%   r$   r   r   r   r   )r   r   constantr&   )axisN)ry   r1   )r
   rz   r   r   rV   r   rZ   r   rM   rN   r|   padrT   maxr   astypemaximumr   r   cliprintnewaxisrX   rQ   zerosr   r}   Tr   )r   r\   
block_size	symmetric
abs_scalesr   r   wr   r   
num_blocksr   	blob_sizer   r   r   r   padded_kblockedr   r   r   zero_pointsw_tr   r   quantizes                              r	   $_matmulnbits_blockwise_quantize_impl2CudaQuantizer._matmulnbits_blockwise_quantize_implm  s    4y_
NN  "%%emm4??AGGIwwvUVZU[[\]^^?Z[eZffghiinq(Z7
Dy&*t3	qyI\bo5M: .A)F[ 6M: ".H1}FF1v8a<'89:Fiiz:GVVBFF7O!4;;BJJG"**UbJccFZZ(<(@(@AF&Arzz9I2J(J KTX__`b`h`hiI"Z/77AIqy((A9#=RXXNBKAqRSRVUVRVJBWZ]B]1>	!Q1* 5 ; ;A >>>?1>	!Q1* 5 ; ;A >>>?IaQRTUTXWXTXjDY\_D_deCee?#((A	
Q1'<z#ZbdbjbjkK##G,e.>.>v.FHXHXYdHeee""133'((A95RXXF1/<hhAIJNq#8:V^`^f^fg7Q7S44,0AI(;P#v{J1PVVF^F(%*:*:6*BEDTDTU`Daaar   F)r   return_zero_pointsr   flatten_qweightr   c          	         [         R                  U UUUUUS9u  pn
U(       a-  UR                  UR                  S   S5      R	                  5       nU(       a  XU
4$ X4$ )ak  Quantize one expert with ONNX Runtime's MatMulNBits blockwise encoding.

``weights`` has logical shape ``[N, K]``. Returns raw flattened storage
``[N, ceil(K/block_size)*ceil(block_size/pack)]`` and block scales
``[N, ceil(K/block_size)]`` by default. Set ``flatten_qweight=False`` for
the MatMulNBits initializer shape
``[N, ceil(K/block_size), ceil(block_size/pack)]``.
Set ``return_zero_points=True`` to also return packed block zero-points.
Symmetric quantization uses the full ``[-8, 7]`` / ``[-128, 127]`` range
by default. Set ``unsigned_full_range=False`` to use the legacy
``[-7, 7]`` / ``[-127, 127]`` range.
r   r   r   r   rH   )r   r   rT   rM   rZ   )r   r\   r   r   r   r   r   r   r   r   r   s              r	   matmulnbits_blockwise_quantize,CudaQuantizer.matmulnbits_blockwise_quantize  sn    0 (5'Y'Y! 3 (Z (
$ oogmmA&6;FFHGK//r   )r   r   r   r   c          	        [        5       n[        U5      n[        U5      n[        U5      nUS;  a  [        SU S35      eUS:X  a  SOSn	X);  a  [        SU	 SU S	U S35      eU R                  u  pX-  S
:w  a  [        SU SU S35      e[        R                  U UUUUUS9u  pn[        nU" UR                  U
S5      R                  5       XX5      n[        R                  " U5      R                  [        R                  5      R                  UR                  5      nUR                  " [        R                  " U5      5      nU(       a  UX4$ UU4$ )a  Quantize and CUDA-prepack one MatMulNBits weight initializer.

``weights`` has logical shape ``[N, K]``. Returns ``B`` with the standard
MatMulNBits initializer shape ``[N, K/block_size, block_size*bits/8]``
and scales with shape ``[N, K/block_size]``.

The ``force_arch`` value selects the mixed-GEMM weight layout and must match
the ``weight_prepacked`` attribute set on the MatMulNBits node:

* ``force_arch=80`` (default): SM80/Ampere layout, consumed by the SM80 kernel
  (also used on newer GPUs via the compatibility path). Use ``weight_prepacked=1``.
* ``force_arch=90``: SM90/Hopper layout, consumed by the native SM90 TMA/WGMMA
  kernel. Use ``weight_prepacked=2``. Requires ``block_size`` in {64, 128}.
rv   z3force_arch must be 80 (SM80) or 90 (SM90), but got ru   rw   )rJ   @   rC   )r   rC   zblock_size must be one of z for force_arch=z
, but got r   r   #) must be divisible by block_size () for CUDA-prepacked weights.r   rH   )r
   rz   rN   rM   r   r   r   rT   r   r|   r   rP   rQ   r   r}   )r   r\   r   r   r   r   r   r   r   allowed_block_sizesr   r   r   r   r   r   r   s                    r	   (matmulnbits_prepacked_blockwise_quantize6CudaQuantizer.matmulnbits_prepacked_blockwise_quantize  sw   4 4y_
_
X%RS]R^^_`aa 0:R/?mY0,-@,AAQR\Q]]ghrgsstu  }}>Qs1#%HTqrss'4'Y'Y! 3 (Z (
$ ,M(1'//!R2H2N2N2PRSX\iF#((2::7==I!!""6"6v">?6..v~r   c          	     T   [        U5      n[        U5      nU R                  u  pSU-  n
X-  S:w  a  [        SU	 SU S35      eX-  S:w  a  [        SU SU
 S35      e[        R	                  U UUUUUS	9u  pn[
        nU" UR                  US
5      R                  5       XX5      n[        R                  " U5      R                  [        R                  5      R                  XU
-  5      n[        5       nUR                  " [        R                  " U5      5      nU(       a  XU4$ X4$ )a  Quantize one expert and CUTLASS-prepack it for CUDA QMoE fpA_intB GEMM.

``weights`` has logical shape ``[N, K]``. Returns ``qweight`` with shape
``[K, N/pack]`` and block scales with shape ``[N, K/block_size]``.
Set ``return_zero_points=True`` to also return packed block zero-points.
r%   r   r   r   r   r   r   z! for QMoE blockwise quantization.r   rH   )rz   rM   rN   r   r   r   rT   r   r|   r   rP   rQ   r
   r   r}   )r   r\   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   s                    r	   !qmoe_prepacked_blockwise_quantize/CudaQuantizer.qmoe_prepacked_blockwise_quantize  s3   $ 4y_
}}Dy>Qs1#%HTqrss8q=s1#%<TFBcdee'4'Y'Y! 3 (Z (
$ ,M(1'//!R2H2N2N2PRSX\iF#((2::14iH!!""6"6v">?;..~r   c                  [        5       nU R                  5       R                  5       R                  5       n U R                  n[        U5      n[        U5      nUS:X  a  U(       a  SOSu  pgnO$US:X  a  U(       a  SOSu  pgnO[        SU S35      eUS	   n	X-   S
-
  U-  n
X-  U	-
  nUS:  aG  [        U5      nXS	'   UR                  " XR                  U R                  S9nUR                  " X/S	S9nOU nUR                  " / USS	 QU
PUP76 nUR                  " UR                  " U5      S	S9S   nUR                  " UU-  SS9nUR                   " UUR#                  S	5      -  5      nUR                  " UXg5      nUS:X  a  UR%                  UR&                  5      R                  " / USS	 QX-  P76 nUS:  a
  USSU* 24   nUS-   R%                  UR(                  5      n[        U5      nUS	   S
-   S-  US	'   UR                  " UUR(                  U R                  S9nUSSSS24   S-  USSS24'   UR                  S	   S
:  a4  USSUSS
SS24   R                  S	   24==   USS
SS24   S-  S-  -  ss'   OSUR%                  UR&                  5      R                  " / USS	 QX-  P76 nUS:  a
  USSU* 24   nUR                  U5      nUR                  5       UR                  5       4$ )a)  Quantize one expert with a pure-PyTorch symmetric blockwise encoding.

This helper is useful for non-CUDA reference paths. Unlike the pybind-backed
helpers above, it pads the last dimension when it is not divisible by
``block_size`` and returns storage with the same leading shape as ``weights``.
r$   )r   r/   r%   )r   r/   r/   r%   )r   rK   rC   )r   rK   rK   z;CUDA blockwise quantization only supports 4 or 8 bits, got ru   rH   r   r   rx   rF   Ng:0yE>r   .r&   r1   )r
   r   r   rZ   rM   rz   rN   listr   ry   r    rS   rP   r   r   r   r   rL   rV   rU   rQ   )r   r\   r   r   r   ri   r   r   r   last_dimr   pad_size	pad_shapepaddingweights_paddedreshaped_weightsblock_max_absr   r   quantized_flatquantized_uint4packed_shaper   s                          r	   symmetric_blockwise_quantize*CudaQuantizer.symmetric_blockwise_quantizeD  s$    .."&&(335 4y_
196I
z%DQY<O(8Ue%DZ[_Z``abcc!"%+a/J>
*X5a<^,I$bMkk)==XG"YY'9rBN$N)..\s0C\Z\Q[\		%)),<"=2FqI]]:EKK 063C3CB3G GH	KK	46	19&\\%**5::iN3B<OiQ[QhiN!|!/ZxiZ!@-155ekkBO/L .r 2Q 61<Lkk,ekk'..YG-c14a4i83>GCFO$$R(1,CsADqDy9??CCCDY\^_^bab^bYbIcfiIinoHooDll5::.33b^CR5Hb*JabG!|!#z	z/2ll>2G{{}fjjl**r   r   N)r   torch.Tensorr\   rz   r   boolreturn!tuple[torch.Tensor, torch.Tensor]rw   )r   r   r\   rz   r   r   r   rz   r   r   r   r   )r   r   r\   rz   r   rz   r   r   r   r   r   r   r   z/tuple[torch.Tensor, torch.Tensor, torch.Tensor])r   r   r\   rz   r   rz   r   r   r   r   r   r   r   r   r   r   r   Stuple[torch.Tensor, torch.Tensor] | tuple[torch.Tensor, torch.Tensor, torch.Tensor])r   r   r\   rz   r   rz   r   rz   r   r   r   r   r   r   r   r   r   r   )
r   r   r\   rz   r   rz   r   r   r   r   )__name__
__module____qualname____firstlineno____doc__staticmethodr   r   r   r   r   r   r   __static_attributes__r   r   r	   r   r     s    
 %)	1E1E1E "	1E
 
+1E 1Ef 
 	F %)FFF F 	F "F 
+F FB AbAbAb Ab
 Ab Ab "Ab 
9Ab AbF  #( $$($$$ $
 $ !$ $ $ "$ 
]$ $L 
 	; #($(;;; ; 	; ; !; ; "; 
]; ;z 
 	+ #( $(+++ + 	+ + !+ + "+ 
]+ +Z  %)>+>+>+ >+
 ">+ 
+>+ >+r   r   )r   r   )r   None)r\   rz   r]   rz   r   )
r   rz   r   rz   r\   rz   r   rz   r   z
np.ndarray)r   
__future__r   	functoolsloggingtypingr   r   r|   	getLoggerr   r   r   r
   r   r   	lru_cacher   r!   rr   r   r   r   r   r   r	   <module>r	     s   , #     


H
%s. Q  n*b!)H8s+ s+r   