
    Pi9                        d dl Z d dlmZmZmZ d dlZd dlmZ d dlm	Z	 ej
        j        Z G d de          Z G d de          Z G d	 d
e j                  ZdedededefdZej        j         G d dej        j                              Zej        j         G d dej        j                              Zdej        dfdej        dej        dej        dee         dee         dee         fdZ G d dej                  ZdS )    N)Dict
NamedTupleOptional)DTensor)to_fp8_saturatedc                   L    e Zd ZU dZdZeed<   dZeed<   dZeed<   dZ	eed<   dS )ScaledMMConfiga  
    Configuration for the scaled_mm in the forward and backward pass.

    Attributes:
        emulate (bool): Whether to emulate the matmuls in fp32.
        use_fast_accum (bool): Whether to use the fast-accumulation option for scaled_mm.
        fp8_output (bool): Whether to output the result of the scaled_mm in fp8.
        pad_inner_dim (bool): Whether to pad the inner dimension of a and b with 0s.
                              This is needed for matmuls not aligned to 16.
    Femulateuse_fast_accum
fp8_outputpad_inner_dimN)
__name__
__module____qualname____doc__r
   bool__annotations__r   r   r        y/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/torchao/float8/float8_training_tensor.pyr	   r	   .   s^         	 	 GT ND   JM4r   r	   c                       e Zd ZU dZ edddd          Zeed<    edddd          Zeed<    edddd          Zeed<   dS )LinearMMConfiga  
    Configuration for different gemm operations in LinearMM.

    This configuration is not user-facing and exists for convenience,
    allowing Float8TrainingTensor to use the right config based on which gemm
    from gemms with outputs `output`, `grad_input`, `grad_weight` is being called.

    Attributes:
        output (ScaledMMConfig): Configuration for the output gemm.
        grad_input (ScaledMMConfig): Configuration for the grad_input gemm.
        grad_weight (ScaledMMConfig): Configuration for the grad_weight gemm.
    FToutput
grad_inputgrad_weightN)	r   r   r   r   r	   r   r   r   r   r   r   r   r   r   @   s~           ,^E4FFFNFFF!/ueU!K!KJKKK"0.ue"L"LKLLLLLr   r   c                       e Zd ZdZdZdZdZdS )GemmInputRolea  
    Given a Float8TrainingTensor, the enum below describes the expected role of this
    tensor in the three gemms present in the fw + bw pass of a Linear layer.
    This is used to choose the right config for a float8 gemm when the
    gemm is performed.
    inputweightgrad_outputN)r   r   r   r   INPUTWEIGHTGRAD_OUTPUTr   r   r   r   r   S   s)          EFKKKr   r   a_rolea_linear_mm_configb_roleb_linear_mm_configc                    | t           j        u r?|t           j        u r1|j        |j        k    sJ d|j         d|j                     |j        S | t           j        u r?|t           j        u r1|j        |j        k    sJ d|j         d|j                     |j        S | t           j        u r?|t           j        u r1|j        |j        k    sJ d|j         d|j                     |j        S t          d|  d|           )Nz"linear_mm_config.output mismatch: z vs z&linear_mm_config.grad_input mismatch: z'linear_mm_config.grad_weight mismatch: zunexpected a_role z and b_role )r   r!   r"   r   r#   r   r   AssertionError)r$   r%   r&   r'   s       r   choose_scaled_mm_configr*   a   sI    $$$=3G)G)G!(,>,EEEEk1C1JkkPbPikk FEE "((	=,	,	,=;O1O1O!,0B0MMMMw5G5RwwXjXuww NMM ",,	=,	,	,=;N1N1N!-1C1OOOOz6H6TzzZlZxzz POO "--N&NNfNNOOOr   c                       e Zd ZdZedej        dfdej        dej        dej	        de
e         de
e         de
e         fd	            Zed
             ZdS )_ToFloat8ConstrFuncz
    A differentiable conversion to fp8.
    * forward: convert from high precision to float8
    * backward: pass the gradient without changes
    Ntensorscalefloat8_dtypelinear_mm_configgemm_input_roleaxiswise_dimc           	         |                     t          j                  |z  }t          ||          }t	          |t
                    rt	          |t
                    s
J d            |j        }	|j        }
|                                }|                                }t          |||j
        |||          }t          j        ||	|
d|                                |                                          S t          |||j
        |||          S )a  
        This function will apply the scaling, and then convert to a Float8TrainingTensor

        Note:
        We will call this function with a DTensor subclass. Ideally this would be an aten OP
        that DTensor could overload to ensure proper semantics. There are some techincal issues
        with that composing with FakeTensor, so we special case here.

        DTensor Invariant: DTensor must always be the outer most tensor subclass
        z>Expected Float8 scale to be a DTensor if bits_fp8 is a DTensor)r0   r1   r2   F)	run_checkshapestride)totorchfloat32r   
isinstancer   device_mesh
placementsto_localFloat8TrainingTensordtype
from_localsizer6   )ctxr-   r.   r/   r0   r1   r2   tensor_scaledbits_fp8	bits_meshbits_placements
local_bitslocal_scaleinner_float8_tensors                 r   forwardz_ToFloat8ConstrFunc.forward   s,   . 		%-0058#M<@@h(( 	eW--  P - !,I&1O!**,,J..**K"6!1 /)# # # %#mmoo((    $L-+%
 
 
 	
r   c                     |d d d d d fS Nr   rB   gs     r   backwardz_ToFloat8ConstrFunc.backward   s    $dD$..r   )r   r   r   r   staticmethodr   r!   r8   Tensorr?   r   r   intrJ   rO   r   r   r   r,   r,   z   s           6:3@3F&*9
 9
9
 |9
 k	9

 #>29
 "-09
 sm9
 9
 9
 \9
v / / \/ / /r   r,   c                   >    e Zd ZdZed             Zed             ZdS )_FromFloat8ConstrFuncz
    A differentiable conversion from fp8.
    * forward: convert from float8 to high precision
    * backward: pass the gradient without changes
    c                 P    |j                             |j                  |j        z  S rL   )_datar7   _orig_dtype_scale)rB   r-   s     r   rJ   z_FromFloat8ConstrFunc.forward   s     |v122V]BBr   c                     |d d fS rL   r   rM   s     r   rO   z_FromFloat8ConstrFunc.backward   s    $}r   N)r   r   r   r   rP   rJ   rO   r   r   r   rT   rT      sW          C C \C   \  r   rT   	hp_tensorsr/   r0   r1   r2   c                 @    t                               | |||||          S )a  
    Given a high precision tensor `hp_tensor` and a precalculated scale `s`,
    scales `hp_tensor` by `s` and returns a `Float8TrainingTensor` of the result.

    Autograd-aware, the derivative is pass-through.
    DTensor-aware, if the input is a DTensor the output will be DTensor(Float8TrainingTensor).

    Args:
        hp_tensor: the tensor to convert
        s: the scale to use to convert the tensor
        float8_dtype: the float8 dtype to use
        linear_mm_config: Defines the configuration for the scaled_mm for
          the 3 fwd/bwd gemms of linear
        gemm_input_role: Defines the role of this tensor (input, weight or grad_output) in
          the 3 fwd/bwd gemms of linear
        axiswise_dim: for rowwise scaling, contains the axis scaled across
    )r,   apply)rZ   r[   r/   r0   r1   r2   s         r   hp_tensor_and_scale_to_float8r^      s*    2 $$1l$4o|  r   c                   R   e Zd ZU dZej        ed<   ej        ed<   ej        ed<   eed<   e	ed<   e
e         ed<   g dZe	j        d	fd
ej        dej        dej        de
e         de
e	         de
e         fdZd Zd Zedefd            Zd Zedd            Zej        j        Zd	S )r>   a^  
    Note: this is **not** a public API and is only intended to be used
    inside of this repository. Please file an issue if you would benefit
    from this being a public API.

    A Python-only Float8 tensor subclass.  Contains:
    * `_data`: the underlying e4m3 or e5m2 data
    * `_scale`: the scale used to scale the original fp32 tensor. We multiply
      by scale to go from fp32 range to fp8 range, and divide by scale to go
      from fp8 range to fp32 range. Scale is guaranteed to have a shape compatible
      with `_data`. For example:
      - if scaling is tensorwise, `_scale` is a scalar tensor
      - if scaling is axiswise and _data.shape is [3, 5], `_scale` could have
        shape [1, 5] or [3, 1]. `axiswise_dim` defines the scaling axis.
      - if scaling is axiswise and _data.shape is [2, 3, 5], `_scale` could have
        shape [1, 1, 5] or [2, 1, 1]. `axiswise_dim` defines the scaling
        axis. Non-one entries which are not the first or last element are not
        supported.
    * `_orig_dtype`: the original dtype of the tensor used to create this
      tensor.
    * `_axiswise_dim`: for axiswise scaling only, contains the axis scales
      across. Only values of 0 or -1 are supported.

    Intended usage of this abstraction:
    1. to bundle raw data + fp8 metadata together for easy passing through
       Python PyTorch systems.
    2. Float8-aware user code can use the private fields on these tensors
       to call into float8 operations.
    3. Float8-agnostic user code can use these tensors as is - they will
       convert to original precision in `__torch_dispatch__`.
    rV   rX   rW   _linear_mm_config_gemm_input_role_axiswise_dim)rV   rX   rW   r`   ra   rb   Ndatar.   
orig_dtyper0   r1   r2   c           
      t   t           j                            | |                                |                                |                                ||j        |j        |j                  }||_	        ||_
        ||_        ||nt                      |_        ||_        |dv sJ d|             ||_        |S )N)stridesstorage_offsetr?   layoutrequires_graddevice)Nr   zunsupported axiswise_dim )r8   rQ   _make_wrapper_subclassrA   r6   rg   rh   ri   rj   rV   rX   rW   r   r`   ra   rb   )clsrc   r.   rd   r0   r1   r2   selfs           r   __new__zFloat8TrainingTensor.__new__"  s     |22IIKKKKMM..00;,; 3 	
 	
 
% 0 <.BRBR 	 !0},,,.X,.X.X,,,)r   c                     d| j         j         d| j         d| j         d| j         d| j         d|                                  S )NzFloat8TrainingTensor(lp_dtype=z, scale=z, linear_mm_config=z, axiswise_dim=z
gemm_input_role=z
as_orig_prec=)rV   r?   rX   r`   rb   ra   to_original_precisionrn   s    r   __repr__zFloat8TrainingTensor.__repr__A  s     |
0@  |  |$+  |  |jn  kA  |  |  RV  Rd  |  |  x|  xM  |  |  ^b  ^x  ^x  ^z  ^z  |  |  	|r   c                 D    | j         | j        | j        | j        d}ddg|fS )NrW   r`   ra   rb   rV   rX   ru   )rn   rB   s     r   __tensor_flatten__z'Float8TrainingTensor.__tensor_flatten__D  s8    +!%!7 $ 5!/	
 
 "C''r   inner_tensorsc           	          t          |           dk    sJ t          | d         | d         |d         |d         |d         |d                   S )N   rV   rX   rW   r`   ra   rb   )lenr>   )rw   metadata
outer_sizeouter_strides       r   __tensor_unflatten__z)Float8TrainingTensor.__tensor_unflatten__M  s_    =!!Q&&&&#'"(#]#()'(_%
 
 	
r   c                 6    t                               |           S rL   )rT   r]   rr   s    r   rq   z*Float8TrainingTensor.to_original_precisionY  s    $**4000r   c                      ddl m}  fdt          fd|D                       st          S ||v r ||         |||          S t	          d| d          )Nr   )FLOAT8_OPS_TABLEc                     t          |           pGt          t          j        j        j        |           p#t          t          j        j        j        |           S rL   )
issubclassr8   _subclassesfake_tensor
FakeTensorfunctional_tensorFunctionalTensor)typerm   s    r   allowed_subclasseszCFloat8TrainingTensor.__torch_dispatch__.<locals>.allowed_subclassesi  sP    3%% e/;FMM%7H$ r   c              3   .   K   | ]} |          V  d S rL   r   ).0tr   s     r   	<genexpr>z:Float8TrainingTensor.__torch_dispatch__.<locals>.<genexpr>r  s/      88Q%%a((888888r   zattempting to run z, this is not supported)torchao.float8.float8_opsr   allNotImplementedNotImplementedError)rm   functypesargskwargsr   r   s   `     @r   __torch_dispatch__z'Float8TrainingTensor.__torch_dispatch__\  s     	?>>>>>
	 	 	 	 	 8888%88888 	"!!###)#D)$f===!"Tt"T"T"TUUUr   rL   )r   r   r   r   r8   rQ   r   r?   r   r   r   rR   	__slots__r!   ro   rs   rv   rP   r   r~   rq   classmethodr   _C_disabled_torch_function_impl__torch_function__r   r   r   r>   r>      s}         @ <L%%%%####C=     I 4A3F&* l | K	
 #>2 "-0 sm   >| | |( ( ( 	
D 	
 	
 	
 \	
1 1 1 V V V [V: ?r   r>   )enumtypingr   r   r   r8   torch.distributed._tensorr   torchao.float8.float8_utilsr   opsatenr	   r   Enumr   r*   _dynamoallow_in_graphautogradFunctionr,   rT   r!   rQ   r?   rR   r^   r>   r   r   r   <module>r      s    - - - - - - - - - -  - - - - - -      y~<         Z      $M M M M MZ M M M&
  
  
  
  
 DI 
  
  
 PP&P P '	P P P P2 E/ E/ E/ E/ E/%.1 E/ E/ E/P     EN3   ( 26/</B"& || + ~.	
 m, 3-   <H@ H@ H@ H@ H@5< H@ H@ H@ H@ H@r   