o
    ý°“iX  ã                   @   s|   d dl Z d dlmZmZmZ g d¢Zdefdd„Zdede jde jfd	d
„Zde jde jfdd„Z	de jde jfdd„Z
dS )é    N)ÚBFLOAT16_DATAÚFP4_E2M1_DATAÚQuantizationArgs)Úmaybe_convert_from_mxfp4_expÚgenerate_mxfp4_scalesÚround_to_power_2Úshould_generatre_mxfp4_scalesÚargsc                 C   s   | j dko| jdko| jdkS )Né   Úfloaté    )Únum_bitsÚtypeÚ
group_size)r	   © r   úe/home/ubuntu/.local/lib/python3.10/site-packages/compressed_tensors/quantization/utils/mxfp4_utils.pyr   !   s   r   ÚscaleÚreturnc                 C   s<   |j }t| ƒr| tj¡d }d| tj¡ }| |¡S |S )a  
    Converts mxfp4 scales. Scales are powers of 2, with the
    exponents stored in uint8. Converts to dense dtype so that
    they can be applied to the weights and activations during QDQ

    :param scale: uint8 exponent scale
    :param dtype: dense dtype
    é   g       @)Údtyper   ÚtoÚtorchÚint32r   )r	   r   Úoriginal_dtypeÚ	scale_expr   r   r   r   %   s   
r   Úxc                 C   st   | j tjksJ ‚|  tj¡ tj¡} dtjt	j d > }dtj
d > d tj> }t | | |¡}| tj¡ tj¡S )a¹  
    Round values to the closest power of 2.
    This is done by masking the values with BFLOAT16_SIGN_EXPONENT_MASK
    which essentially removes the mantissa and keeps the exponent.
    i.e the closest power of 2 for the input_value.

    E.g:
        0.0825 = 1.32 (mantissa) x 2**-4 (exponent)
        0.0825 ==> -4 (exponent) + 127 = 123 = 01111011 (8 bits for bfloat16)
        0.0825 ==> 0.32 (mantissa) = 0101001 (7 bits for bfloat16)
        0.0825 == 0b01111011_0101001 (bfloat16)
        0b01111011_0101001 & 111111111_0000000 == 0b01111011_0000000
        Keep the exponent + sign bit to give you the closest power of 2, 0.0625

    :param x: tensor to round to closest power of 2
    é   )r   r   Úbfloat16ÚviewÚuint16r   r   r   Úmantissar   ÚexponentÚbitwise_and)r   ÚBFLOAT16_VAL_TO_ADDÚBFLOAT16_SIGN_EXPONENT_MASKÚblock_max_uintr   r   r   r   8   s   þÿr   c                 C   s    t | ƒ}dt t |¡¡ d S )a  
    Generate mxfp4 scales. The scales require the following steps
    1. Round to the closest power of 2
    2. Convert to exponent

    Called when calculating qparams using observers.

    :param x: tensor to round to closest power of 2
    :returns scales as exponents
    r   é   )r   r   ÚfloorÚlog2)r   Úscale_power_2r   r   r   r   Z   s   r   )r   Ú*compressed_tensors.quantization.quant_argsr   r   r   Ú__all__r   ÚTensorr   r   r   r   r   r   r   Ú<module>   s   
ÿÿ
þ"