o
    Ti                     @   s  d dl Z d dlZd dlmZ d dlm  mZ d dlmZ d dl	m
Z
mZ d dlmZ d dlZd dlmZ d dlmZ d dlmZ d dlmZmZmZ d d	lmZ d dlZejZg Zg Zi Z d
Z!G dd de"Z#dd Z$dddZ%dddZ&dedefddZ'ddede(de)fddZ*ddede(de)fdd Z+ddede)fd!d"Z,ddede)fd#d$Z-d%d& Z.		 			'		dd(d)Z/dd+d,Z0		*	 	 	*	*dd-d.Z1				/	0dd1d2Z2			0dded3e
e3 dee d4ee d5e(f
d6d7Z4			0dded8e3dee d4ee d5e(f
d9d:Z5					'	/	0dded;ee d<ee dee d4ee d=e)d>e(d5e(fd?d@Z6dAdB Z7ddDdEZ8			F		ddGdHZ9ddJdKZ:ddLdMdNZ;d*d*ddOdPdQZ<dRdS Z=dTdU Z>d*d*ddOdVdWZ?ddLdXdYZ@d*ddZd[d\ZAd]d^ ZBd_d` ZCdadb ZDdcdd ZEdedf ZFdgdh ZGdidj ZHdkdl ZIdmdn ZJdodp ZKdqdr ZLdsdt ZMejNeLejOeLejPeLejQeMejReMejSeMiZTde!fdudvZUde!fdwdxZVde!fdydzZWde!fd{d|ZXde!fd}d~ZYde!fddZZdd Z[dd Z\dd Z]dg i d'd'dd*d*d'dddfddZ^dS )    N)partial)ListOptional)OrderedDict)get_accelerator)logger)MoE)FORWARD_GLOBAL_TIMERBACKWARD_GLOBAL_TIMERSTEP_GLOBAL_TIMER)required_torch_version   c                   @   s   e Zd ZdZd ddZd!ddZdd	 Zd
d Zdd Zd"ddZ	d"ddZ
d"ddZd"ddZdd Zd#ddZd$ddZdS )%FlopsProfilera  Measures the latency, number of estimated floating-point operations and parameters of each module in a PyTorch model.

    The flops-profiler profiles the forward pass of a PyTorch model and prints the model graph with the measured profile attached to each module. It shows how latency, flops and parameters are spent in the model and which modules or layers could be the bottleneck. It also outputs the names of the top k modules in terms of aggregated latency, flops, and parameters at depth l with k and l specified by the user. The output profile is computed for each batch of input.
    The DeepSpeed flops profiler can be used with the DeepSpeed runtime or as a standalone package.
    When using DeepSpeed for model training, the flops profiler can be configured in the deepspeed_config file and no user code change is required.

    If using the profiler as a standalone package, one imports the flops_profiler package and use the APIs.

    Here is an example for usage in a typical training workflow:

        .. code-block:: python

            model = Model()
            prof = FlopsProfiler(model)

            for step, batch in enumerate(data_loader):
                if step == profile_step:
                    prof.start_profile()

                loss = model(batch)

                if step == profile_step:
                    flops = prof.get_total_flops(as_string=True)
                    params = prof.get_total_params(as_string=True)
                    prof.print_model_profile(profile_step=profile_step)
                    prof.end_profile()

                loss.backward()
                optimizer.step()

    To profile a trained model in inference, use the `get_model_profile` API.

    Args:
        object (torch.nn.Module): The PyTorch model to profile.
    N        c                 C   s"   || _ || _|| _d| _d| _d S )NF)model	ds_enginerecompute_fwd_factorstartedfunc_patched)selfr   r   r    r   _/home/ubuntu/.local/lib/python3.10/site-packages/deepspeed/profiling/flops_profiler/profiler.py__init__C   s
   
zFlopsProfiler.__init__c                 C   sP   t d |   t  t  t  dd }| jt||d d| _	d| _
dS )a  Starts profiling.

        Extra attributes are added recursively to all the modules and the profiled torch.nn.functionals are monkey patched.

        Args:
            ignore_list (list, optional): the list of modules to ignore while profiling. Defaults to None.
        zFlops profiler startedc                 S   s   |r
t | |v r
d S t | tv r!t| ds| tt |  | _d S dd }t| ds0| || _dd }t| ds?| || _dd	 }t| d
sN| || _dd }t| ds_| || _	d S d S )N__flops_handle__c                 S   s   t g  tg  d S Nmodule_flop_countappendmodule_mac_countmoduleinputr   r   r   pre_hookc      
zLFlopsProfiler.start_profile.<locals>.register_module_hooks.<locals>.pre_hook__pre_hook_handle__c                 S   s\   t r,|  jtdd t d D 7  _t   |  jtdd td D 7  _t  d S d S )Nc                 S      g | ]}|d  qS    r   .0elemr   r   r   
<listcomp>l       zaFlopsProfiler.start_profile.<locals>.register_module_hooks.<locals>.post_hook.<locals>.<listcomp>c                 S   r%   r&   r   r(   r   r   r   r+   n   r,   )r   	__flops__sumpop__macs__r   r    r!   outputr   r   r   	post_hookj   s     zMFlopsProfiler.start_profile.<locals>.register_module_hooks.<locals>.post_hook__post_hook_handle__c                 S   s   t    t | _d S r   )r   synchronizetime__start_time__r   r   r   r   start_time_hookt   r#   zSFlopsProfiler.start_profile.<locals>.register_module_hooks.<locals>.start_time_hook__start_time_hook_handle__c                 S   s&   t    |  jt | j 7  _d S r   )r   r6   __duration__r7   r8   r2   r   r   r   end_time_hook{   s   
zQFlopsProfiler.start_profile.<locals>.register_module_hooks.<locals>.end_time_hook__end_time_hook_handle__)
typeMODULE_HOOK_MAPPINGhasattrregister_forward_hookr   register_forward_pre_hookr$   r5   r:   r=   )r    ignore_listr"   r4   r9   r<   r   r   r   register_module_hooksX   s&   




z:FlopsProfiler.start_profile.<locals>.register_module_hooksrC   TN)r   inforeset_profile_patch_functionals_patch_tensor_methods_patch_miscellaneous_operationsr   applyr   r   r   )r   rC   rD   r   r   r   start_profileJ   s   
*
zFlopsProfiler.start_profilec                 C   s<   | j r| jrt  t  t  d| _dd }| j| dS )z[Stop profiling.

        All torch.nn.functionals are restored to their originals.
        Fc                 S   s   t | dr| j  | `t | dr| j  | `t | dr$| j  | `t | dr0| j  | `t | dr>| j  | `d S d S )Nr$   r5   r   r:   r=   )r@   r$   remover5   r   r:   r=   r    r   r   r   remove_profile_attrs   s    









z8FlopsProfiler.stop_profile.<locals>.remove_profile_attrsN)r   r   _reload_functionals_reload_tensor_methods _reload_miscellaneous_operationsr   rK   r   rO   r   r   r   stop_profile   s   zFlopsProfiler.stop_profilec                    s$   dd   fdd}| j | dS )zLResets the profiling.

        Adds or resets the extra attributes.
        c                 S   s^   d}t |}d}t| dd|r&zt| j|d }W n	 ty%   Y nw |  ||  fS )z
            Return the number of parameters in the layer, whether the layer is an MoE layer,
            and its expert parallelism size if so
            ep_size_r   
group_name N)lengetattr
startswithintrV   
ValueErrornumelelement_size)paramprefixoffsetexpert_parallelismr   r   r   get_param_count_and_ep   s   z;FlopsProfiler.reset_profile.<locals>.get_param_count_and_epc                    s   d| _ d| _d | _ | _| _ fdd|  D }|D ]*\}}}|s%|nd}|r+|nd}|| }|  j|7  _|  j|7  _|  j|7  _qd| _d| _d S )Nr   c                 3   s    | ]} |V  qd S r   r   )r)   prc   r   r   	<genexpr>   s    zJFlopsProfiler.reset_profile.<locals>.add_or_reset_attrs.<locals>.<genexpr>)r.   r1   
__params____expert_params____model_expert_params__
parametersr8   r;   )r    rj   
num_paramsrb   per_param_sizeparamsexpert_paramsmodel_expert_paramsre   r   r   add_or_reset_attrs   s   
z7FlopsProfiler.reset_profile.<locals>.add_or_reset_attrsN)r   rK   )r   rp   r   re   r   rG      s   zFlopsProfiler.reset_profilec                 C   s:   | j sdS |   d| _ dd }| j| td dS )znEnds profiling.

        The added attributes and handles are removed recursively on all the modules.
        NFc                 S   sj   t | dr| `t | dr| `t | dr| `t | dr| `t | dr#| `t | dr*| `t | dr3| `d S d S )Nr.   r1   rg   rh   ri   r8   r;   )r@   r.   r1   rg   rh   ri   r8   r;   rN   r   r   r   rO      s   






z7FlopsProfiler.end_profile.<locals>.remove_profile_attrszFlops profiler finished)r   rT   r   rK   r   rF   rS   r   r   r   end_profile   s   zFlopsProfiler.end_profileFc                 C      t | j}|rt|S |S )a  Returns the total flops of the model.

        Args:
            as_string (bool, optional): whether to output the flops as string. Defaults to False.

        Returns:
            The number of multiply-accumulate operations of the model forward pass.
        )get_module_flopsr   number_to_string)r   	as_stringtotal_flopsr   r   r   get_total_flops      
	zFlopsProfiler.get_total_flopsc                 C   rr   )a  Returns the total MACs of the model.

        Args:
            as_string (bool, optional): whether to output the flops as string. Defaults to False.

        Returns:
            The number of multiply-accumulate operations of the model forward pass.
        )get_module_macsr   macs_to_string)r   ru   
total_macsr   r   r   get_total_macs   rx   zFlopsProfiler.get_total_macsc                 C   rr   )zReturns the total duration of the model forward pass.

        Args:
            as_string (bool, optional): whether to output the duration as string. Defaults to False.

        Returns:
            The latency of the model forward pass.
        )get_module_durationr   duration_to_string)r   ru   total_durationr   r   r   get_total_duration   rx   z FlopsProfiler.get_total_durationc                 C   s    | j j| j j }|rt|S |S )a  Returns the total number of parameters stored per rank.

        Args:
            as_string (bool, optional): whether to output the parameters as string. Defaults to False.

        Returns:
            The total number of parameters stored per rank.
        )r   rh   rg   params_to_string)r   ru   total_paramsr   r   r   get_total_params  s   	zFlopsProfiler.get_total_paramsc                 C   s6   | j  D ]\}}t|trt|dr|j  S qdS )N enable_expert_tensor_parallelismF)r   named_modules
isinstancer   r@   r   )r   _r    r   r   r   $is_expert_tensor_parallelism_enabled  s
   
z2FlopsProfiler.is_expert_tensor_parallelism_enabledr'   r-   Tc                    s  | j sdS ddl}ddl}d}d}	|r7|dkr7|j|j|}
|j|
s,||
 |j}t	|d}	|	|_| 
 }|  |  |  d}d }}| jrl| jj| jj }| jjrl|  rd| jjnd}| jj| }|| _| _| _td td| d td	 d
}| jrt|d| jj t|d| jj t|d| jj t|d| j  | jjrt|d|dk t|dt |dkrt|dt||  t|dt| t|dt| n
t|dt| t|dt t|dt| t|dt|| jr| jjnd  |  }| jr;| j  r;| j!t"#dd }t|dt$| t|dt%||  | jr| j  rd| j& }| j!t'#dd }| j!t(#dd }t|dt$| t|d|dd t%|| |  t|d!|d dd"t%|d | ||   t|d#t$| || | }t|d$t$| t|d%|d dd&t%|d | |  | j | jj }t|d't)|| t* fd(d)  fd*d+}d,d- }| j+| td. | j,||d/ |r*td0 td1 td2 t| j | j+| td3 |r@||_|	-  dS dS )4a  Prints the model graph with the measured profile attached to each module.

        Args:
            profile_step (int, optional): The global training step at which to profile. Note that warm up steps are needed for accurate time measurement.
            module_depth (int, optional): The depth of the model to which to print the aggregated module information. When set to -1, it prints information from the top to the innermost modules (the maximum depth).
            top_modules (int, optional): Limits the aggregated profile output to the number of top modules specified.
            detailed (bool, optional): Whether to print the detailed model profile.
            output_file (str, optional): Path to the output file. If None, the profiler prints to stdout.
        Nr   rW   wr'   zO
-------------------------- DeepSpeed Flops Profiler --------------------------zProfile Summary at step :a  Notations:
data parallel size (dp_size), model parallel size(mp_size),
number of parameters (params), number of multiply-accumulate operations(MACs),
number of floating-point operations (flops), floating-point operations per second (FLOPS),
fwd latency (forward propagation latency), bwd latency (backward propagation latency),
step (weights update latency), iter latency (sum of fwd, bwd and step latency)
z{:<70}  {:<8}zworld size: zdata parallel size: zmodel parallel size: zbatch size per GPU: z#expert tensor parallelism enabled: zparams per GPU: zparams of model: z   non-expert params of model: z   expert params of model: z,params of model = params per GPU * mp_size: zfwd MACs per GPU: zfwd flops per GPU: z2fwd flops of model = fwd flops per GPU * mp_size: F     @@zfwd latency: z5fwd FLOPS per GPU = fwd flops per GPU / fwd latency: r   zbwd latency: zbwd FLOPS per GPU = gz$ * fwd flops per GPU / bwd latency: zfwd+bwd FLOPS per GPU = z* * fwd flops per GPU / (fwd+bwd latency): zstep latency: ziter latency: zFLOPS per GPU = z% * fwd flops per GPU / iter latency: zsamples/second: c                    s   | j | j }t| }t| }t| }dt|r"td|  tnddt	|r4td|  tnddt
| rFtd|   tndt|rRt|| tndg}|  }|ra|| d|S )Nz{} = {:g}% Paramsd   r   z{} = {:g}% MACsz{} = {:g}% latencyz, )rg   rh   rs   ry   r}   formatr   roundDEFAULT_PRECISIONrz   r~   flops_to_stringoriginal_extra_reprr   join)r    rm   flopsmacsdurationitemsr   )r   r{   r   r   r   
flops_repr  s*   


z5FlopsProfiler.print_model_profile.<locals>.flops_reprc                    s:     | }| j|kr| j| _|| _| j| jksJ d S d S r   )__get__
extra_reprr   )r    flops_extra_repr)r   r   r   add_extra_repr  s   

z9FlopsProfiler.print_model_profile.<locals>.add_extra_reprc                 S   s   t | dr| j| _| `d S d S )Nr   )r@   r   r   rN   r   r   r   del_extra_repr  s   
z9FlopsProfiler.print_model_profile.<locals>.del_extra_reprzW
----------------------------- Aggregated Profile per GPU -----------------------------)module_depthtop_moduleszW
------------------------------ Detailed Profile per GPU ------------------------------zEach module profile is listed after its name in the following order: 
params, percentage of total params, MACs, percentage of total MACs, fwd latency, percentage of total fwd latency, fwd FLOPSat  
Note: 1. A module can have torch.nn.module or torch.nn.functional to compute logits (e.g. CrossEntropyLoss). They are not counted as submodules, thus not to be printed out. However they make up the difference between a parent's MACs (or latency) and the sum of its submodules'.
2. Number of floating-point operations is a theoretical estimation, thus FLOPS computed using that could be larger than the maximum system throughput.
3. The fwd latency listed in the top module's profile is directly captured at the module forward function in PyTorch, thus it's less than the fwd latency shown above which is captured in DeepSpeed.
zN------------------------------------------------------------------------------).r   sysos.pathpathdirnameabspathexistsmakedirsstdoutopenrw   r|   r   r   r   r   rg   mp_world_sizehas_moe_layersr   ri   r   r   rm   printr   
world_sizedp_world_sizetrain_micro_batch_size_per_gpur   rz   rt   wall_clock_breakdowntimersr	   elapsedr~   r   r   r
   r   r   r   rK   print_model_aggregated_profileclose)r   profile_stepr   r   detailedoutput_filer   osoriginal_stdoutfdir_pathrv   expert_tensor_parallelismtotal_model_expert_paramstotal_model_nonexpert_paramsline_fmtfwd_latency
bwd_factorbwd_latencystep_latencyiter_latencysamples_per_iterr   r   r   )r   r   r{   r   r   print_model_profile  s   






z!FlopsProfiler.print_model_profilec           
         s@  i }t | jdstd dS  fdd  | jd| |}|dkr't|d }td	| d
 t|D ]j}t|t|| }dd t||  dd ddd| D }dd t||  dd ddd| D }dd t||  dd ddd| D }	td| d td|  td|  td|	  q3dS )a`  Prints the names of the top top_modules modules in terms of aggregated time, flops, and parameters at depth module_depth.

        Args:
            module_depth (int, optional): the depth of the modules to show. Defaults to -1 (the innermost modules).
            top_modules (int, optional): the number of top modules to show. Defaults to 1.
        r.   zbno __flops__ attribute in the model, call this function after start_profile and before end_profileNc                    s   ||vri ||< | j j|| vrg d|| | j j< || | j j d  t| 7  < || | j j d  | j| j 7  < || | j j d  t| 7  < t| j dk}|rf| 	 D ]} ||d | q[d S d S )N)r   r   r   r   r'   r   )
	__class____name__ry   rg   rh   r}   rX   _modulesr   children)r    
curr_depthrF   has_childrenchildwalk_moduler   r   r     s    $ zAFlopsProfiler.print_model_aggregated_profile.<locals>.walk_moduler   r-   r'   zTop zK modules in terms of params, MACs or fwd latency at different model depths:c                 S      i | ]\}}|t |d  qS r   )rz   r)   kvr   r   r   
<dictcomp>      z@FlopsProfiler.print_model_aggregated_profile.<locals>.<dictcomp>c                 S      | d d S )Nr'   r   r   itemr   r   r   <lambda>      z>FlopsProfiler.print_model_aggregated_profile.<locals>.<lambda>T)keyreversec                 S   r   r&   )r   r   r   r   r   r     r   c                 S   s   | d d S Nr'   r   r   r   r   r   r     r   c                 S   r   )r   )r~   r   r   r   r   r     r   c                 S   r   )Nr'   r   r   r   r   r   r   r     r   zdepth r   z    params      - z    MACs        - z    fwd latency - )r@   r   r   rX   rangeminsortedr   )
r   r   r   rF   depthd	num_items	sort_macssort_params	sort_timer   r   r   r     s4      z,FlopsProfiler.print_model_aggregated_profile)Nr   r   F)r'   r-   r'   TN)r-   r'   )r   
__module____qualname____doc__r   rL   rT   rG   rq   rw   r|   r   r   r   r   r   r   r   r   r   r      s    
$
<'




 'r   c                 C   s   d}| D ]}||9 }q|S r   r   )dimsrd   r   r   r   r   _prod  s   
r   c                 C   s"   |j d }|  | }d| |fS )Nr   r   )shaper]   )r!   weightbiasout_featuresr   r   r   r   _linear_flops_compute  s   
r   Fc                 C      |   dfS Nr   r]   r!   inplacer   r   r   _relu_flops_compute     r   r!   r   c                 C   r   r   r   )r!   r   r   r   r   _prelu_flops_compute  r   r         ?alphar   c                 C   r   r   r   )r!   r   r   r   r   r   _elu_flops_compute  r   r   {Gz?negative_slopec                 C   r   r   r   )r!   r   r   r   r   r   _leaky_relu_flops_compute  r   r   c                 C   r   r   r   r   r   r   r   _relu6_flops_compute  r   r   c                 C   r   r   r   r   r   r   r   _silu_flops_compute   r   r  c                 K   r   r   r   )r!   kwargsr   r   r   _gelu_flops_compute$  r   r  Tc	           	      C   r   r   r   )	r!   kernel_sizestridepaddingdilation	ceil_modecount_include_paddivisor_overridereturn_indicesr   r   r   _pool_flops_compute(  s   	r  r'   c                 C   s  |j d | | j d ksJ | j d }| j d }|j d }	t|j dd  }
t| j dd  }t|}t|tu r;|n|f| }t|tu rH|n|f| }t|try|dkr[d| }n+|dkrxd}t||
D ]\}}||d  }||d f7 }qfnt|tr|}n|f| }g }t|D ]#\}}|d||   || |
| d  d  ||  d }|	| q|	| }t
t|
| | }|t
t| }|| }d| }d}|d ur|	| }t
|| t
|fS )Nr'   r   r   validr   samer   )r   listrX   r>   tupler   strzip	enumerater   r[   r   )r!   r   r   r  r  r  groups
batch_sizein_channelsout_channelskernel_dims
input_dimslengthstrides	dilationspaddingsr   r   total_paddingoutput_dimsidx	input_dim
output_dimfilters_per_channelconv_per_position_macsactive_elements_countoverall_conv_macsoverall_conv_flops
bias_flopsr   r   r   _conv_flops_compute4  sT   







r)  c                 C   s  | j d }| j d }	|j d }
t|j dd  }t| j dd  }t|}t|tu r-|n|f| }t|tu r:|n|f| }t|tu rG|n|f| }g }t|D ]#\}}|d||   || || d  d  ||  d }|| qRt|tu r~|n||f}t|tu r|n||f}t|tu r|n||f}|
| }tt||	 | }|tt| }|| }d| }d}|d ur|
| tt| }t|| t|fS )Nr   r'   r   )	r   r  rX   r>   r  r  r   r[   r   )r!   r   r   r  r  output_paddingr  r  r  r  r  r  r  r  r  r  r  r  r   r!  r"  r#  r$  r%  r&  r'  r(  r   r   r   _conv_trans_flops_computea  sB   




r+  皙?h㈵>c           
      C   sF   |d u}|r|   |rd dfS d dfS |   |rdnd }	|	dfS )N      r   r   r'   r   )
r!   running_meanrunning_varr   r   trainingmomentumeps
has_affiner   r   r   r   _batch_norm_flops_compute  s
   
r6  normalized_shaper   r4  c                 C   &   |d u}|   |rd dfS d dfS Nr.  r/  r   r   )r!   r7  r   r   r4  r5  r   r   r   _layer_norm_flops_compute  s   r:  
num_groupsc                 C   r8  r9  r   )r!   r;  r   r   r4  r5  r   r   r   _group_norm_flops_compute  s   r<  r0  r1  use_input_statsr3  c           	      C   s&   |d u}|   |rd dfS d dfS r9  r   )	r!   r0  r1  r   r   r=  r3  r4  r5  r   r   r   _instance_norm_flops_compute  s   
r>  c                  O   s   | d }| dd }|d u rt| dkr| d }|d ur4t|ts&t|tr.tt|dfS t|dfS | dd }|d u rHt| dkrH| d }|d usPJ d| }t|trmt|t|krm|tt|9 }|dfS ||t| 9 }|dfS )Nr   sizer'   scale_factorr   z-either size or scale_factor should be defined)getrX   r   r  r  r[   r   r]   )argsr  r!   r?  r@  r   r   r   r   _upsample_flops_compute  s$   rC     c                 C   r   r   r   )r!   dim_stackleveldtyper   r   r   _softmax_flops_compute  r   rH         @c                 C      dS N)r   r   r   )r!   r   padding_idxmax_norm	norm_typescale_grad_by_freqsparser   r   r   _embedding_flops_compute  s   	rQ        ?c                 C   rJ  rK  r   )r!   rd   r2  r   r   r   r   _dropout_flops_compute  s   rS  )outc                C   s    t | j|jd  }d| |fS )z/
    Count flops for the matmul operation.
    r-   r   r   r   )r!   otherrT  r   r   r   r   _matmul_flops_compute  s   rW  )betar   rT  c                C   *   t |j|jd  }d| t | j |fS )z.
    Count flops for the addmm operation.
    r-   r   rU  )r!   mat1mat2rX  r   rT  r   r   r   r   _addmm_flops_compute     r\  c           	      G   s   |  dd} dd |D }tdd | D  }dd t|D }| |} d	d |D }tj| g|R d
did }|dD ]}d| v rYt	t
|dd }|df  S q@td)z/
    Count flops for the einsum operation.
     rW   c                 S      g | ]}|j qS r   r   r)   or   r   r   r+         z)_einsum_flops_compute.<locals>.<listcomp>c                 s        | ]}|  r|d fV  qdS r   Nisalphar)   r   r   r   r   rf         z(_einsum_flops_compute.<locals>.<genexpr>c                 S      i | ]\}}t |d | qS a   ordr)   ixr   r   r   r         z)_einsum_flops_compute.<locals>.<dictcomp>c                 S      g | ]}t |qS r   npzerosr)   sr   r   r   r+         optimizeoptimalr'   
optimized flopr   r-   r   zUnsupported einsum operation.)replacer   keysr  	translateru  einsum_pathsplitlowerr[   floatNotImplementedError)	equationoperandsinput_shapesletter_ordermappingnp_arrsoptimlineflopr   r   r   _einsum_flops_compute  s   
r  c            
      G   s   | ^ }}dd |D }t dd |D  }dd t|D }||}dd |D }tj|g|R dd	id
 }|dD ]}d| v rXtt	|dd }	|	df  S q?t
d)z6
    Count flops for the einops.einsum operation.
    c                 S   r_  r   r`  ra  r   r   r   r+     rc  z0_einops_einsum_flops_compute.<locals>.<listcomp>c                 s   rd  re  rf  rh  r   r   r   rf   "  ri  z/_einops_einsum_flops_compute.<locals>.<genexpr>c                 S   rj  rk  rm  ro  r   r   r   r   #  rr  z0_einops_einsum_flops_compute.<locals>.<dictcomp>c                 S   rs  r   rt  rw  r   r   r   r+   &  ry  rz  r{  r'   r|  r}  r   r-   r   z$Unsupported einops.einsum operation.)r   r  r  r  ru  r  r  r  r[   r  r  )
rB  r  r  r  r  r  r  r  r  r  r   r   r   _einops_einsum_flops_compute  s   

r  c                C   rY  )z5
    Count flops for the tensor addmm operation.
    r-   r   rU  )r   rZ  r[  rX  r   rT  r   r   r   r   _tensor_addmm_flops_compute0  r]  r  c                C   
   t | |S r   _elementwise_flops_compute)r!   rV  rT  r   r   r   _mul_flops_compute8     
r  )r   rT  c                C   r  r   r  )r!   rV  r   rT  r   r   r   _add_flops_compute<  r  r  c           
      C   s   t | st |rt|jdfS dS t |st| jdfS t| j}t|j}t||}g }t|D ]'}||k r?| j| nd}||k rJ|j| nd}||krV|| q4|| q4t|}	|	dfS )Nr   )r'   r   r'   )torch	is_tensorr   r   rX   maxr   r   )
r!   rV  	dim_input	dim_othermax_dimfinal_shaperp  in_iot_ir   r   r   r   r  @  s$   





r  c                 O   sJ   t | j|jd  }|t | jdd |jd  |jd  7 }d| |fS )zE
    Count flops for the scaled_dot_product_attention operation.
    Nr-   r   rU  )qr   r   rB  r  r   r   r   r   _attn_flops_computeY  s   *r  c                    s.   | | j t<  fdd}| j |_ |S )Nc                     sP    | i |\}}t rt d |f tr!|r!td |f | i |S )Nr-   r   )rB  kwdsr   r   funcFlopComputenameoldFuncr   r   newFuncg  s   zwrapFunc.<locals>.newFunc)__str__old_functions)funcr  r  r   r  r   wrapFuncb  s   r  c                   C   s  t tjtt_t tjtt_t tjtt_t tjtt_t tjt	t_t tj
t	t_
t tjt	t_t tjtt_t tjtt_t tjtt_t tjtt_t tjtt_ttdr`t tjtt_t tjtt_t tjtt_t tjtt_t tjt t_t tj!t"t_!t tj#t$t_#t tj%t$t_%t tj&t$t_&t tj't$t_'t tj(t$t_(t tj)t$t_)t tj*t$t_*t tj+t$t_+t tj,t$t_,t tj-t$t_-t tj.t$t_.t tj/t$t_/t tj0t1t_0t tj2t1t_2t tj3t4t_3t tj5t6t_5t7ddrt tj8t9t_8d S d S )NsilurI  )min_version):r  Flinearr   conv1dr)  conv2dconv3dconv_transpose1dr+  conv_transpose2dconv_transpose3drelur   prelur   elur   
leaky_relur   relu6r   r@   r  r  gelur  
batch_normr6  
layer_normr:  instance_normr>  
group_normr<  
avg_pool1dr  
avg_pool2d
avg_pool3d
max_pool1d
max_pool2d
max_pool3dadaptive_avg_pool1dadaptive_avg_pool2dadaptive_avg_pool3dadaptive_max_pool1dadaptive_max_pool2dadaptive_max_pool3dupsamplerC  interpolatesoftmaxrH  	embeddingrQ  r   scaled_dot_product_attentionr  r   r   r   r   rH   t  sL   
rH   c                   C   s   t tjtt_t tjjttj_t tjjttj_t tjtt_t tjjttj_t tjtt_t tjjttj_t tjt	t_t tjjt
tj_t tjtt_t tjjttj_t tjtt_t tjjttj_t tjtt_t tjt
t_d S r   )r  r  matmulrW  Tensor
__matmul__mmbmmaddmmr\  r  mulr  addr  einsumr  baddbmmr   r   r   r   rI     s   rI   c                   C   s   t tjtt_d S r   )r  einopsr  r  r   r   r   r   rJ        rJ   c                   C   s  t tjj t_t tjj t_t tjj t_t tjj t_t tjj t_t tjj t_t tj	j t_	t tj
j t_
t tjj t_t tjj t_t tjj t_t tjj t_ttdr`t tjj t_t tjj t_t tjj t_t tjj t_t tjj t_t tjj t_t tjj t_t tjj t_t tjj t_t tjj t_t tjj t_t tjj t_t tjj t_t tjj t_t tjj t_t tjj t_t tj j t_ t tj!j t_!t tj"j t_"t tj#j t_#t tj$j t_$t tj%j t_%d S )Nr  )&r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r@   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r   r   r   rP     sF   
rP   c                   C   s   t tjj t_t tjjj tj_t tjj t_t tjjj tj_t tjj t_t tjjj tj_t tjj t_t tjjj tj_t tjj t_t tjjj tj_t tj	j t_	t tjj	j tj_	t tj
j t_
t tjj t_d S r   )r  r  r  r  r  r  r  r  r  r  r  r  r   r   r   r   rQ     s   rQ   c                   C   s   t tjj t_d S r   )r  r  r  r  r   r   r   r   rR     r  rR   c                 C   s   |j d }| d|j d  |j d  | 7 } | d|j d  |j d  | 7 } t|tjtjfr5| |j7 } | S t|tjtjfrS| |j7 } | |jd 7 } | |jd 7 } | S t|tjtj	fry| |jd 7 } | |j|j |j 7 } | |j|j |j 7 } | S )Nr   r   r'   rD  r/  )
r   r   nnRNNRNNCellhidden_sizeGRUGRUCellLSTMLSTMCell)r   
rnn_modulew_ihw_hh
input_size
gates_sizer   r   r   
_rnn_flops  s    
  

r  c                 C   s   d}|d }|j d }|j d }| j}t|D ]H}| dt| }	| dt| }
|dkr3| j}n| j}t|| |	|
|}| jr_| dt| }| dt| }||j d |j d  7 }q||9 }||9 }| j	ro|d9 }|  j
t|7  _
d S )Nr   r'   weight_ih_lweight_hh_l	bias_ih_l	bias_hh_lr   )r   
num_layersr   __getattr__r  r  r  r  r   bidirectionalr.   r[   )r  r!   r3   r   inpr  
seq_lengthr  rp  r  r  r  b_ihb_hhr   r   r   _rnn_forward_hook"  s,   

r  c                 C   s   d}|d }|j d }| d}| d}|j d }t|| |||}| jr;| d}	| d}
||	j d |
j d  7 }||9 }|  jt|7  _d S )Nr   	weight_ih	weight_hhr'   bias_ihbias_hh)r   r  r  r   r.   r[   )rnn_cell_moduler!   r3   r   r  r  r  r  r  r  r  r   r   r   _rnn_cell_forward_hook>  s   





r  c                 C      t | ||d dS )Nunits	precisionMACsrt   )r   r  r  r   r   r   rz   Z     rz   c                 C   s   |d u rC| dkrd\}}nb| dkrd\}}nY| dkrd\}}nP| dkr(d\}}nG| d	ks0| d
kr5d\}}n:| dkr>d\}}n1d\}}n,|dkrJd}n%|dkrQd}n|dkrXd}n|dkr_d}n|dkrfd}n	|dkrmd}nd	}t | | |dd| S )N   mB)r  T    eA)r  G    .A)r
  Mr   )r   Kr'   r   )r'   rW   MbP?)r  m)ư>ur  r	  r  r  r  r  r  r   r^  )r   )numr  r  	magnituder   r   r   rt   ^  s8   






rt   c                 C   r  )Nr   FLOPSr  )r   r  r  r   r   r   r     r  r   c                 C   r  )Nr   Br  )br  r  r   r   r   bytes_to_string  r  r  c                 C   s.   |r| ddn|}t| ||d dd S )Nr  r	  r   )r~  rt   strip)
params_numr  r  r   r   r   r     s   r   c                 C   r  )Nr   rx  r  )r   r  r  r   r   r   r~     r  r~   c                 C   $   | j }|  D ]}|t|7 }q|S r   )r.   r   rs   r    r/   r   r   r   r   rs        rs   c                 C   r  r   )r1   r   ry   r  r   r   r   ry     r  ry   c                 C   s,   | j }|dkr|  D ]}|t|7 }q|S r   )r;   r   r}   )r    r   r  r   r   r   r}     s
   r}   r-   forwardc                 C   s  t | tjs
J dt| }|   |dur\t|tu s J dt|dks*J dzt	dj
g |R t|  jt|  jd}W n tyX   t	d
g |R }Y nw |g}t|dkslt|dkslJ d	td
 t|D ]-}|r|dkr| |i |}|dkr| j|i |}qu|dkr| | }|dkr| j| }qu|j|d |r|dkr| |i |}|dkr| j|i |}n|dkr| | }|dkr| j| }| }| }| }|r|j|||||
d |  |	rt|t|t|fS |||fS )a\  Returns the total floating-point operations, MACs, and parameters of a model.

    Example:

    .. code-block:: python

        model = torchvision.models.alexnet()
        batch_size = 256
        flops, macs, params = get_model_profile(model=model, input_shape=(batch_size, 3, 224, 224)))

    Args:
        model ([torch.nn.Module]): the PyTorch model to be profiled.
        input_shape (tuple): input shape to the model. If specified, the model takes a tensor with this shape as the only positional argument.
        args (list): list of positional arguments to the model.
        kwargs (dict): dictionary of keyword arguments to the model.
        print_profile (bool, optional): whether to print the model profile. Defaults to True.
        detailed (bool, optional): whether to print the detailed model profile. Defaults to True.
        module_depth (int, optional): the depth into the nested modules. Defaults to -1 (the inner most modules).
        top_modules (int, optional): the number of top modules to print in the aggregated profile. Defaults to 3.
        warm_up (int, optional): the number of warm-up steps before measuring the latency of each module. Defaults to 1.
        as_string (bool, optional): whether to print the output as string. Defaults to True.
        output_file (str, optional): path to the output file. If None, the profiler prints to stdout.
        ignore_modules ([type], optional): the list of modules to ignore during profiling. Defaults to None.

    Returns:
        The number of floating-point operations, multiply-accumulate operations (MACs), and parameters in the model.
    zmodel must be a PyTorch moduleNzinput_shape must be a tupler'   z*input_shape must have at least one elementr   )rG  devicer   z;args and/or kwargs must be specified if input_shape is NonezFlops profiler warming-up...r  generaterE   )r   r   r   r   r   )r   r  Moduler   evalr>   r  rX   r  ones	new_emptynextrj   rG  r  StopIterationr   rF   r   r  rL   rw   r|   r   r   rq   rt   rz   r   )r   input_shaperB  r  print_profiler   r   r   warm_upru   r   ignore_modulesmodeprofr!   r   r   r   rm   r   r   r   get_model_profile  sn   (

 



r+  r   r   )r   F)r   F)Nr   NFTNN)Nr'   r   r'   r'   )Nr'   r   r   r'   r'   )NNFr,  r-  )NNr-  )NNNNTr,  r-  )NrD  N)NNrI  FF)rR  TF)_r7   r  torch.nnr  torch.nn.functional
functionalr  	functoolsr   typingr   r   collectionsr   numpyru  deepspeed.acceleratorr   deepspeed.utilsr   deepspeed.moe.layerr   deepspeed.utils.timerr	   r
   r   deepspeed.utils.torchr   r  r  r   r   r  r   objectr   r   r   r   r   r  boolr   r   r   r  r  r  r)  r+  r6  r[   r:  r<  r>  rC  rH  rQ  rS  rW  r\  r  r  r  r  r  r  r  r  rH   rI   rJ   rP   rQ   rR   r  r  r  r  r  r  r  r  r  r?   rz   rt   r   r  r   r~   rs   ry   r}   r+  r   r   r   r   <module>   sB     d



0
2






	;'"	