
    h9                     t   S SK r S SKJrJrJr  S SKrS SKJr  S SKJ	r	  \R                  R                  r " S S\5      r " S S\5      r " S	 S
\ R                  5      rS\S\S\S\4S jr\R"                  R$                   " S S\R&                  R(                  5      5       r\R"                  R$                   " S S\R&                  R(                  5      5       rS\R.                  S4S\R0                  S\R0                  S\R2                  S\\   S\\   S\\   4S jjr " S S\R0                  5      rg)    N)Dict
NamedTupleOptional)DTensor)to_fp8_saturatedc                   R    \ rS rSr% SrSr\\S'   Sr\\S'   Sr	\\S'   Sr
\\S'   Srg	)
ScaledMMConfig.   a  
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_dim N)__name__
__module____qualname____firstlineno____doc__r   bool__annotations__r   r   r   __static_attributes__r       _/home/james-whalen/.local/lib/python3.13/site-packages/torchao/float8/float8_training_tensor.pyr	   r	   .   s1    	 GT ND JM4r   r	   c                   z    \ rS rSr% Sr\" SSSS5      r\\S'   \" SSSS5      r\\S'   \" SSSS5      r	\\S'   Sr
g	)
LinearMMConfig@   a  
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_weightr   N)r   r   r   r   r   r	   r   r   r   r   r   r   r   r   r   r   @   sH     ,E4FFNF!/ueU!KJK"0ue"LKLr   r   c                   $    \ rS rSrSrSrSrSrSrg)GemmInputRoleS   z
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_outputr   N)	r   r   r   r   r   INPUTWEIGHTGRAD_OUTPUTr   r   r   r   r!   r!   S   s     EFKr   r!   a_rolea_linear_mm_configb_roleb_linear_mm_configc                    U [         R                  L aZ  U[         R                  L aG  UR                  UR                  :X  d!   SUR                   SUR                   35       eUR                  $ U [         R                  L aZ  U[         R                  L aG  UR
                  UR
                  :X  d!   SUR
                   SUR
                   35       eUR
                  $ U [         R                  L aZ  U[         R                  L aG  UR                  UR                  :X  d!   SUR                   SUR                   35       eUR                  $ [        SU  SU 35      e)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   s`    $$$=3G3G)G!((,>,E,EE 	
01C1J1J0K4PbPiPiOjk	
E "(((	=,,	,=;O;O1O!,,0B0M0MM 	
45G5R5R4SSWXjXuXuWvw	
M ",,,	=,,	,=;N;N1N!--1C1O1OO 	
56H6T6T5UUYZlZxZxYyz	
O "---1&fXNOOr   c                       \ rS rSrSr\S\R                  S4S\R                  S\R                  S\R                  S\\   S\\   S	\\   4S
 jj5       r\S 5       rSrg)_ToFloat8ConstrFuncz   z
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           	         UR                  [        R                  5      U-  n[        Xs5      n[	        U[
        5      (       a  [	        U[
        5      (       d   S5       eUR                  n	UR                  n
UR                  5       nUR                  5       n[        UUUR                  UUUS9n[
        R                  " UU	U
SUR                  5       UR                  5       S9$ [        UUUR                  UUUS9$ )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)r6   r7   r8   F)	run_checkshapestride)totorchfloat32r   
isinstancer   device_mesh
placementsto_localFloat8TrainingTensordtype
from_localsizer<   )ctxr3   r4   r5   r6   r7   r8   tensor_scaledbits_fp8	bits_meshbits_placements
local_bitslocal_scaleinner_float8_tensors                 r   forward_ToFloat8ConstrFunc.forward   s    . 		%--058#M@h((eW-- P- !,,I&11O!**,J..*K"6!1 /)# %%#mmo(  $LL-+%
 	
r   c                     US S S S S 4$ Nr   rH   gs     r   backward_ToFloat8ConstrFunc.backward   s    $dD$..r   r   )r   r   r   r   r   staticmethodr!   r&   r>   TensorrE   r   r   intrP   rV   r   r   r   r   r1   r1   z   s      6:3@3F3F&*9
9
 ||9
 kk	9

 #>29
 "-09
 sm9
 9
v / /r   r1   c                   8    \ rS rSrSr\S 5       r\S 5       rSrg)_FromFloat8ConstrFunc   z
A differentiable conversion from fp8.
* forward: convert from float8 to high precision
* backward: pass the gradient without changes
c                 f    UR                   R                  UR                  5      UR                  -  $ rS   )_datar=   _orig_dtype_scale)rH   r3   s     r   rP   _FromFloat8ConstrFunc.forward   s$    ||v112V]]BBr   c                     US S 4$ rS   r   rT   s     r   rV   _FromFloat8ConstrFunc.backward   s    $}r   r   N)	r   r   r   r   r   rX   rP   rV   r   r   r   r   r\   r\      s1     C C  r   r\   	hp_tensorsr5   r6   r7   r8   c                 0    [         R                  XX#XE5      $ )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
)r1   apply)re   rf   r5   r6   r7   r8   s         r   hp_tensor_and_scale_to_float8ri      s    2 $$lo r   c                      \ rS rSr% Sr\R                  \S'   \R                  \S'   \R                  \S'   \	\S'   \
\S'   \\   \S'   / S	Qr\
R                  S
4S\R                  S\R                  S\R                  S\\	   S\\
   S\\   4S jjrS rS r\S\4S j5       rS r\SS j5       r\R0                  R2                  rSrg
)rD      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__`.
r_   ra   r`   _linear_mm_config_gemm_input_role_axiswise_dim)r_   ra   r`   rl   rm   rn   Ndatar4   
orig_dtyper6   r7   r8   c                 b   [         R                  R                  U UR                  5       UR	                  5       UR                  5       UUR                  UR                  UR                  S9nXl	        X'l
        X7l        Ub  UO	[        5       Ul        XWl        US;   d
   SU 35       eXgl        U$ )N)stridesstorage_offsetrE   layoutrequires_graddevice)Nr   zunsupported axiswise_dim )r>   rY   _make_wrapper_subclassrG   r<   rs   rt   ru   rv   r_   ra   r`   r   rl   rm   rn   )clsro   r4   rp   r6   r7   r8   selfs           r   __new__Float8TrainingTensor.__new__"  s     ||22IIKKKM..0;;,,;; 3 	
 
% 0 <.BR 	 !0},X0I,.XX,)r   c                     SU R                   R                   SU R                   SU R                   SU R                   SU R
                   SU R                  5        3$ )NzFloat8TrainingTensor(lp_dtype=z, scale=z, linear_mm_config=z, axiswise_dim=z
gemm_input_role=z
as_orig_prec=)r_   rE   ra   rl   rn   rm   to_original_precisionrz   s    r   __repr__Float8TrainingTensor.__repr__A  s    /

0@0@/A$++Vijn  kA  kA  jB  BQ  RV  Rd  Rd  Qe  ew  x|  xM  xM  wN  N]  ^b  ^x  ^x  ^z  ]{  |  	|r   c                 l    U R                   U R                  U R                  U R                  S.nSS/U4$ )Nr`   rl   rm   rn   r_   ra   r   )rz   rH   s     r   __tensor_flatten__'Float8TrainingTensor.__tensor_flatten__D  s?    ++!%!7!7 $ 5 5!//	
 "C''r   inner_tensorsc           	      h    [        U 5      S:X  d   e[        U S   U S   US   US   US   US   5      $ )N   r_   ra   r`   rl   rm   rn   )lenrD   )r   metadata
outer_sizeouter_strides       r   __tensor_unflatten__)Float8TrainingTensor.__tensor_unflatten__M  sT    =!Q&&&#'"(#]#()'(_%
 	
r   c                 ,    [         R                  U 5      $ rS   )r\   rh   r   s    r   r~   *Float8TrainingTensor.to_original_precisionY  s    $**400r   c                    ^ ^ SSK Jn  U 4S jm[        U4S jU 5       5      (       d  [        $ X;   a  XQ   " XU5      $ [	        SU S35      e)Nr   )FLOAT8_OPS_TABLEc                    > [        TU 5      =(       dc    [        [        R                  R                  R                  U 5      =(       d.    [        [        R                  R
                  R                  U 5      $ rS   )
issubclassr>   _subclassesfake_tensor
FakeTensorfunctional_tensorFunctionalTensor)typery   s    r   allowed_subclassesCFloat8TrainingTensor.__torch_dispatch__.<locals>.allowed_subclassesi  sW    3% e//;;FFM%%77HH$r   c              3   4   >#    U  H  nT" U5      v   M     g 7frS   r   ).0tr   s     r   	<genexpr>:Float8TrainingTensor.__torch_dispatch__.<locals>.<genexpr>r  s     8%Q%a((%s   zattempting to run z, this is not supported)torchao.float8.float8_opsr   allNotImplementedNotImplementedError)ry   functypesargskwargsr   r   s   `     @r   __torch_dispatch__'Float8TrainingTensor.__torch_dispatch__\  sR     	?
	 8%888!!##)$f==!$6tf<S"TUUr   )rn   r_   rm   rl   r`   ra   rS   )r   r   r   r   r   r>   rY   r   rE   r   r!   r   rZ   	__slots__r&   r{   r   r   rX   r   r   r~   classmethodr   _C_disabled_torch_function_impl__torch_function__r   r   r   r   rD   rD      s    @ <<LL%%##C= I 4A3F3F&*ll || KK	
 #>2 "-0 sm>|( 	
D 	
 	
1 V V: ??r   rD   )enumtypingr   r   r   r>   torch.distributed._tensorr   torchao.float8.float8_utilsr   opsatenr	   r   Enumr!   r/   _dynamoallow_in_graphautogradFunctionr1   r\   r&   rY   rE   rZ   ri   rD   r   r   r   <module>r      s`    - -  - yy~~< Z  $MZ M&
 DII 
 PP&P P '	P2 E/%..11 E/ E/P ENN33  ( 26/</B/B"&|||| ++ ~.	
 m, 3-<H@5<< H@r   