
    ¯wgg                         U d dl Z d dlmZmZmZ ddlmZ d dlmZm	Z	m
Z
mZmZmZmZ d dlmZ d dlmZ d dlmZ d d	lmZ d dlZd
dgZe j2                  j4                  Zd Zi Ze
e	e	f   ed<   d Zd3dZ eej@                        ddde!fd       Z" eejF                        d4de!fd       Z$ eejJ                        d4de!fd       Z& eejN                        d4de!fd       Z(	 d3dee!   dee!   dee!   de)de!f
dZ* eejV                  ejX                  g      ddde!fd       Z- eej\                        de!fd       Z/d Z0 eejb                  ejd                  ejf                  g      ddde!fd       Z4d Z5dd deeee!d!f   ee!d!f   ee!d!f   eee!d!f      f      fd"Z6dd deeee!d!f   ee!d!f   ee!d!f   eee!d!f      f      fd#Z7 eejp                  d$%      ddde!fd&       Z9 eejt                  d$%      de!fd'       Z;d( Z< eejz                  ej|                  ej~                  g      ddde!fd)       Z@ eej                  d$%      de!fd*       ZB eej                  d$%      de!fd+       ZDi ej@                  e"ejF                  e$ejJ                  e&ejN                  e(ejV                  e-ejX                  e-ej\                  e/ejb                  e4ejd                  e4ejf                  e4ejz                  e@ej|                  e@ej~                  e@ejp                  e9ejt                  e;ej                  eBej                  eDZd, ZEg d-ZFd. ZGd/ ZHd0 ZId1 ZJ G d2 d
e      ZKy)5    N)tree_maptree_flattentree_unflatten   )ModuleTracker)ListAnyDictOptionalUnionTupleIterator)defaultdict)TorchDispatchModeprodwrapsFlopCounterModeregister_flop_formulac                 R    t        | t        j                        r| j                  S | S N)
isinstancetorchTensorshape)is    ]/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/torch/utils/flop_counter.py	get_shaper      s    !U\\"wwH    flop_registryc                 4     t               d d fd
       }|S )N)out_valc                 F    t        t        ||| f      \  }}} |d|i|S )N	out_shape)r   r   )r#   argskwargsr%   fs       r   nfzshape_wrapper.<locals>.nf   s2    "*9tVW6M"Nfi$6)6v66r    r   r(   r)   s   ` r   shape_wrapperr+      s#    
1X 7 7 Ir    c                       fd}|S )Nc                      st                 fd}t        j                  j                  j	                  |        S )Nc                     t        | t        j                  j                        st	        d|  dt        |              | t        v rt        d|        t        | <   y )Nzlregister_flop_formula(targets): expected each target to be OpOverloadPacket (i.e. torch.ops.mylib.foo), got z which is of type zduplicate registrations for )r   r   _opsOpOverloadPacket
ValueErrortyper!   RuntimeError)targetflop_formulas    r   registerz=register_flop_formula.<locals>.register_fun.<locals>.register&   si    fejj&A&AB Hh0f@A A &"%A&#JKK$0M&!r    )r+   r   utils_pytree	tree_map_)r5   r6   get_rawtargetss   ` r   register_funz+register_flop_formula.<locals>.register_fun"   s7    (6L	1 	%%h8r     )r;   r:   r<   s   `` r   r   r   !   s    & r    )r%   returnc                :    | \  }}|\  }}||k(  sJ ||z  dz  |z  S )zCount flops for matmul.   r=   )	a_shapeb_shaper%   r&   r'   mkk2ns	            r   mm_floprG   7   s3    
 DAqEB7N7q519q=r    c                     t        ||      S )zCount flops for addmm.)rG   
self_shaperA   rB   r%   r'   s        r   
addmm_floprK   B   s     7G$$r    c                 V    | \  }}}|\  }}}	||k(  sJ ||k(  sJ ||z  |	z  dz  |z  }
|
S )z"Count flops for the bmm operation.r@   r=   )rA   rB   r%   r'   brC   rD   b2rE   rF   flops              r   bmm_floprP   G   sK    
 GAq!IBA7N77N7q519q=1DKr    c                     t        ||      S )z&Count flops for the baddbmm operation.rP   rI   s        r   baddbmm_floprS   T   s    
 GW%%r    x_shapew_shaper%   
transposedc                 t    | d   }|r| n|dd }|^}}}	 t        |      t        |      z  |z  |z  |z  dz  }	|	S )a  Count flops for convolution.

    Note only multiplication is
    counted. Computation for bias are ignored.
    Flops for a transposed convolution are calculated as
    flops = (x_shape[2:] * prod(w_shape) * batch_size).
    Args:
        x_shape (list(int)): The input shape before convolution.
        w_shape (list(int)): The filter shape.
        out_shape (list(int)): The output shape after convolution.
        transposed (bool): is the convolution transposed
    Returns:
        int: the number of flops
    r   r@   Nr   )
rT   rU   r%   rV   
batch_size
conv_shapec_outc_infilter_sizerO   s
             r   conv_flop_countr]   \   s]    * J''Y;J 'E4+ 
d;//*<uDtKaODKr    c                     t        | |||      S )zCount flops for convolution.rV   )r]   )
rT   rU   _bias_stride_padding	_dilationrV   r%   r&   r'   s
             r   	conv_floprd      s     7GY:NNr    c                    d }d}	 |
d   r t        |d         }|t        | |||       z  }|
d   rZt        |d         }|r&|t         ||        ||       ||      d      z  }|S |t         ||       ||        ||      d      z  }|S )Nc                 4    | d   | d   gt        | dd        z   S )Nr   r   r@   )list)r   s    r   tzconv_backward_flop.<locals>.t   s$    a%(#d59o55r    r   r   Fr_   )r   r]   )grad_out_shaperT   rU   r`   ra   rb   rc   rV   _output_padding_groupsoutput_maskr%   rh   
flop_countgrad_input_shapegrad_weight_shapes                   r   conv_backward_floprp      s    6JDL 1~$Yq\2ong?OU_Q_``
1~%il3/!N*;QwZK\I]joppJ
  /!G*a6GK\I]joppJr    c                     | \  }}}}|\  }}}	}
|\  }}}}||cxk(  r|k(  r"n J ||cxk(  r|k(  rn J ||
k(  r
|	|k(  r||
k(  sJ d}|t        ||z  ||f||z  ||	f      z  }|t        ||z  ||	f||z  |	|f      z  }|S )z^
    Count flops for self-attention.

    NB: We can assume that value_shape == key_shape
    r   rR   )query_shape	key_shapevalue_shaperM   hs_qd_q_b2_h2s_k_d2_b3_h3_s3d_vtotal_flopss                   r   sdpa_flop_countr      s     !NAq#s"Cc3$Cc3?s?[[qC3[[3#:#*QTX[Q[[[K8QUC-AsC/@AAK8QUC-AsC/@AAKr    c                    t        | ||      S )Count flops for self-attention.r   )rr   rs   rt   r%   r&   r'   s         r   	sdpa_flopr     s     ;	;??r    c                     ddl m} ddlm} t	        | ||f      s| j                         j                         S |g| j                  d      dz
  z  S )z
    If the offsets tensor is fake, then we don't know the actual lengths.
    In that case, we can just assume the worst case; each batch has max length.
    r   )
FakeTensor)FunctionalTensorr   )torch._subclasses.fake_tensorr   #torch._subclasses.functional_tensorr   r   difftolistsize)offsetsmax_lenr   r   s       r   _offsets_to_lengthsr     sI    
 9Dg
,<=>||~$$&&9Q!+,,r    )grad_out.c              #   Z  K   |t        |j                        dk(  sJ t        |j                        dk(  sJ ||j                  | j                  k(  sJ | j                  \  }}	}
|j                  \  }}}|j                  \  }}}|J |J |j                  |j                  k(  sJ t        ||      }t        ||      }t        ||      D ]%  \  }}d|	||
f}d|||f}d|||f}||nd}||||f ' y| j                  |j                  |j                  ||j                  ndf yw)a;  
    Given inputs to a flash_attention_(forward|backward) kernel, this will handle behavior for
    NestedTensor inputs by effectively unbinding the NestedTensor and yielding the shapes for
    each batch element.

    In the case that this isn't a NestedTensor kernel, then it just yields the original shapes.
    N   r   lenr   r   zip)querykeyvaluer   	cum_seq_q	cum_seq_kmax_qmax_k_h_qrw   h_kd_kh_vr   seq_q_lengthsseq_k_lengths	seq_q_len	seq_k_lennew_query_shapenew_key_shapenew_value_shapenew_grad_out_shapes                          r   %_unpack_flash_attention_nested_shapesr     s[    $  399~"""5;;1$$$8>>U[[#@@@kk3ii3kk3$$$$$$)//111+Iu=+Iu=&)-&G 	V"Y	 #y#6OY4M #y#6O4<4Hd!=/CUUU	V 	
++syy%++AUx~~[_
__s   D)D+c              #   `  K   |t        |j                        dk(  sJ t        |j                        dk(  sJ ||j                  | j                  k(  sJ | j                  \  }}}	}
|j                  \  }}}}|j                  \  }}}}|J |J |j                  |j                  k(  sJ t        ||      }t        ||      }t        ||      D ]%  \  }}d|	||
f}d|||f}d|||f}||nd}||||f ' y| j                  |j                  |j                  ||j                  ndf yw)a?  
    Given inputs to a efficient_attention_(forward|backward) kernel, this will handle behavior for
    NestedTensor inputs by effectively unbinding the NestedTensor and yielding the shapes for
    each batch element.

    In the case that this isn't a NestedTensor kernel, then it just yields the original shapes.
    N   r   r   )r   r   r   r   cu_seqlens_qcu_seqlens_kmax_seqlen_qmax_seqlen_kr   r   rw   r   r   r   r   	seqlens_q	seqlens_klen_qlen_kr   r   r   r   s                          r   )_unpack_efficient_attention_nested_shapesr   F  sd    $  399~"""5;;1$$$8>>U[[#@@@1c31c31c3''''''!!\%7%7777'lC	'lC		95 	VLE5 #uc2OUC0M #uc2O4<4Hd!=/CUUU	V 	
++syy%++AUx~~[_
__s   D,D.T)r:   c          	      J    t        | ||||||      }
t        d |
D              S )r   )r   r   r   r   r   r   r   c              3   @   K   | ]  \  }}}}t        |||        y wr   r   .0rr   rs   rt   r   s        r   	<genexpr>z0_flash_attention_forward_flop.<locals>.<genexpr>  )      2KK 	Y<   r   sum)r   r   r   r   r   r   r   r%   r&   r'   sizess              r   _flash_attention_forward_flopr   v  s?    " 2E  6;  r    c           	      J    t        | ||||||      }
t        d |
D              S )r   )r   r   r   r   r   r   r   c              3   @   K   | ]  \  }}}}t        |||        y wr   r   r   s        r   r   z4_efficient_attention_forward_flop.<locals>.<genexpr>  r   r   r   r   )r   r   r   biasr   r   r   r   r&   r'   r   s              r   !_efficient_attention_forward_flopr     s?    " 6!!!!E  6;  r    c                    d}|\  }}}}|\  }	}
}}|\  }}}}| \  }}}}||	cxk(  r|cxk(  r|k(  rn J ||
cxk(  r|cxk(  r|k(  r	n J ||k(  sJ ||k(  r
||k(  r||k(  sJ d}|t        ||z  ||f||z  ||f      z  }|t        ||z  ||f||z  ||f      z  }|t        ||z  ||f||z  ||f      z  }|t        ||z  ||f||z  ||f      z  }|t        ||z  ||f||z  ||f      z  }|S )Nr   rR   )ri   rr   rs   rt   r   rM   ru   rv   rw   rx   ry   rz   r{   r|   r}   r~   r   _b4_h4_s4_d4s                        r   sdpa_backward_flop_countr     sf   K NAq#s"Cc3$Cc3'Cc3!s!c!KKa3&<#&<&<KKKK#:#*33K 8QUC-AsC/@AAK 8QUC-AsC/@AAK8QUC-AsC/@AAK 8QUC-AsC/@AAK8QUC-AsC/@AAKr    c                    t        | |||      S )z(Count flops for self-attention backward.r   )ri   rr   rs   rt   r%   r&   r'   s          r   sdpa_backward_flopr     s    
 $NKKXXr    c
           
      L    t        |||| ||||	      }t        d |D              S )N)r   r   r   r   r   r   r   r   c              3   B   K   | ]  \  }}}}t        ||||        y wr   r   r   rr   rs   rt   ri   s        r   r   z1_flash_attention_backward_flop.<locals>.<genexpr>  +      ?KK 	!iU   r   )r   r   r   r   out	logsumexpr   r   r   r   r&   r'   shapess                r   _flash_attention_backward_flopr     sB    " 3	F  CI  r    c
           
      L    t        |||| ||||	      }t        d |D              S )N)r   r   r   r   r   r   r   r   c              3   B   K   | ]  \  }}}}t        ||||        y wr   r   r   s        r   r   z5_efficient_attention_backward_flop.<locals>.<genexpr>  r   r   r   )r   r   r   r   r   r   r   r   r   r   r&   r'   r   s                r   "_efficient_attention_backward_flopr     sB    " 7!!!!	F  CI  r    c                 ,    t        | t              s| fS | S r   )r   tuple)xs    r   normalize_tupler   .  s    atHr    ) KMBTc                     t        dt        t        t              dz
  t        t	        |             dz
  dz              }t        |   S )Nr   r   r@   r   )maxminr   suffixesstr)numberindexs     r   get_suffix_strr   7  s=     3s8}q(3s6{+;a+?A*EFGEE?r    c                 X    t         j                  |      }| d|z  z  d}|t         |   z   S )Ni  z.3f)r   r   )r   suffixr   r   s       r   convert_num_with_suffixr   >  s2    NN6"E%c*E8E?""r    c                     |dk(  ry| |z  dS )Nr   0%z.2%r=   )numdenoms     r   convert_to_percent_strr   E  s    zEk#r    c                 .     t                fd       }|S )Nc                 B    t        |       \  }} | }t        ||      S r   )r   r   )r&   	flat_argsspecr   r(   s       r   r)   z)_pytreeify_preserve_structure.<locals>.nfK  s'    &t,	4mc4((r    r   r*   s   ` r   _pytreeify_preserve_structurer   J  s     
1X) )
 Ir    c                   
    e Zd ZdZ	 	 	 	 ddeeej                  j                  e	ej                  j                     f      de
dedeeeef      f fdZde
fdZdeeeee
f   f   fd	Zdd
Z fdZ fdZddZd Z xZS )r   a  
    ``FlopCounterMode`` is a context manager that counts the number of flops within its context.

    It does this using a ``TorchDispatchMode``.

    It also supports hierarchical output by passing a module (or list of
    modules) to FlopCounterMode on construction. If you do not need hierarchical
    output, you do not need to use it with a module.

    Example usage

    .. code-block:: python

        mod = ...
        with FlopCounterMode(mod) as flop_counter:
            mod.sum().backward()

    modsdepthdisplaycustom_mappingc                 V   t         |           t        d       | _        || _        || _        |i }|t        j                  dd       i t        |j                         D ci c]   \  }}|t        |dd      r|n
t        |      " c}}| _        t               | _        y c c}}w )Nc                       t        t              S r   )r   intr=   r    r   <lambda>z*FlopCounterMode.__init__.<locals>.<lambda>o  s    +VYJZ r    z<mods argument is not needed anymore, you can stop passing itr@   )
stacklevel_get_rawF)super__init__r   flop_countsr   r   warningswarnr!   itemsgetattrr+   r   mod_tracker)selfr   r   r   r   rD   v	__class__s          r   r  zFlopCounterMode.__init__h  s     	6ABZ6[
!NMMXefg

WeWkWkWmntqRSqwq*e4!-:JJn
 )? os   &%B%r>   c                 N    t        | j                  d   j                               S )NGlobal)r   r  values)r  s    r   get_total_flopszFlopCounterMode.get_total_flops|  s!    4##H-44677r    c                 |    | j                   j                         D ci c]  \  }}|t        |       c}}S c c}}w )a  Return the flop counts as a dictionary of dictionaries.

        The outer
        dictionary is keyed by module name, and the inner dictionary is keyed by
        operation name.

        Returns:
            Dict[str, Dict[Any, int]]: The flop counts as a dictionary.
        )r  r
  dict)r  rD   r  s      r   get_flop_countszFlopCounterMode.get_flop_counts  s3     (,'7'7'='='?@tq!47
@@@s   8c                 >   
 | j                   }|d}dd l}d|_        g d}g } j                         
t	        
      d
 fd}t         j                  j                               D ]?  }|dk(  r	|j                  d      d	z   }||kD  r# |||d	z
        }|j                  |       A d j                  v r8s6t        t        |            D ]  }	d
||	   d   z   ||	   d<     |dd      |z   }t        |      dk(  rg dg}|j                  ||d      S )Ni?B r   T)ModuleFLOPz% TotalFc           	         t        
j                  |    j                               }	|k\  z  	d|z  }g }|j                  || z   t	        |      t        |      g       
j                  |    j                         D ]<  \  }}|j                  |dz   t        |      z   t	        |      t        |      g       > |S )N z - )r   r  r  appendr   r   r
  r   )mod_namer   r   paddingr  rD   r  global_flopsglobal_suffixis_global_subsumedr  s          r   process_modz.FlopCounterMode.get_table.<locals>.process_mod  s     d..x8??ABK+"==EkGFMM("']C&{LA 
 ((288: 1eOc!f,+A}=*1l;  Mr    r  .r   r  )r  0r   )leftrightr&  )headerscolalign)r   tabulatePRESERVE_WHITESPACEr  r   sortedr  keyscountextendranger   )r  r   r)  headerr  r"  mod	mod_depth
cur_valuesidxr  r   r!  s   `         @@@r   	get_tablezFlopCounterMode.get_table  s@   =JJE=E'+$.++-&|4"	, $**//12 	&Ch		#*I5 $S)a-8JMM*%	& t'''0BS[) 6!$vc{1~!5sA6 !1-6Fv;!+,F  B\ ]]r    c                     | j                   j                          | j                  j                          t        |           | S r   )r  clearr  	__enter__r  )r  r  s    r   r8  zFlopCounterMode.__enter__  s7     ""$r    c                     t        |   |  | j                  j                          | j                  r%t	        | j                  | j                               y y r   )r  __exit__r  r   printr5  r   )r  r&   r  s     r   r:  zFlopCounterMode.__exit__  sC    $!!#<<$..,- r    c                 Z    |r|ni } ||i |}| j                  |j                  |||      S r   )_count_flops_overloadpacket)r  functypesr&   r'   r   s         r   __torch_dispatch__z"FlopCounterMode.__torch_dispatch__  s7    !rD#F#  !5!5sD&IIr    c                     || j                   v rY| j                   |   } ||i |d|i}t        | j                  j                        D ]  }| j                  |   |xx   |z  cc<    |S )Nr#   )r!   setr  parentsr  )r  func_packetr   r&   r'   flop_count_funcrm   pars           r   r=  zFlopCounterMode._count_flops  sx    $,,,"00=O($F&F#FJ4++334 A  %k2j@2A 
r    )Nr@   TNr   )r=   N)__name__
__module____qualname____doc__r   r   r   nnr  r   r  boolr
   r	   r  r  r   r  r5  r8  r:  rA  r=  __classcell__)r  s   @r   r   r   T  s    * MQ 7;+5$uxx2G!GHI+ + 	+
 %T#s(^4+(8 8
Ac4S>&9!: 
A:^x.J
r    )Fr   )Lr   torch.utils._pytreer   r   r   module_trackerr   typingr   r	   r
   r   r   r   r   collectionsr   torch.utils._python_dispatchr   mathr   	functoolsr   r  __all__opsatenr   r!   __annotations__r+   r   mmr  rG   addmmrK   bmmrP   baddbmmrS   rM  r]   convolution_convolutionrd   convolution_backwardrp   r   '_scaled_dot_product_efficient_attention#_scaled_dot_product_flash_attention#_scaled_dot_product_cudnn_attentionr   r   r   r   _flash_attention_forwardr   _efficient_attention_forwardr   r   0_scaled_dot_product_efficient_attention_backward,_scaled_dot_product_flash_attention_backward,_scaled_dot_product_cudnn_attention_backwardr   _flash_attention_backwardr   _efficient_attention_backwardr   r   r   r   r   r   r   r   r=   r    r   <module>rk     s    F F ) D D D # :    5
6yy~~
 !#tCH~ ", tww/3 #    tzz"%# % #% txx 
C 
 !
 t||$&C & %& 	%#Y%#Y% Cy% 	%
 	%N (($*;*;<=bf Oux O >O
 t001e e 2eN$ DD@@@@B C EI @WZ @C@	-" +` eE#s(OU38_eCHoxPUVY[^V^P_G``ab+`f -` eE#s(OU38_eCHoxPUVY[^V^P_G``ab-`` t44dC  	 D> t88$G 	 H>6 MMIIIIK L ^b Yps YLY t55tD 	 E@ t994H 	 I@GGWJJ
 	HHh 	LL,	
 	i 	y 	1 	00) 	,,i 	,,i 	99;M 	557I 	557I 	!!#@ 	%%'H  	""$B!" 	&&(J#( $# 
K' Kr    