
    zj.                    t   U d dl mZ d dlZd dlmZ d dl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mZ er3d d	lmZ d d
l	mZ d dlmZ d dlmZ eee         ed         f         Zded<   g Z	 	 d*d+dZd Zd Zd Zd Zd  Z d! Z!d" Z"d# Z#d$ Z$i e
j%        ee
j&        ee
j'        ee
j(        ee
j)        ee
j*        ee
j+        j,        j-        ee
j.        ee
j/        e"e
j0        e"e
j1        ee
j2        ee
j3        e"e
j4        e e
j5        e e
j6        e e
j7        e!e
j8        e!e
j9        e!iZ:	 	 d*d,d)Z;dS )-    )annotationsN)TYPE_CHECKING)	TypeAlias)nn)unwrap_decorators   )Tablestatic_flops)Callable)Tensor)Layer)Program).Nr   _CustomOpsAliasFnetLayer | Program
input_size	list[int]
custom_ops_CustomOpsAlias | Noneprint_detailboolreturnintc                H   t          | t          j                  rCt          | j                  \  }| _        t          j        |          }t          | |||          S t          | t
          j        j	                  rt          | |          S t          j        d           dS )au  Print a table about the FLOPs of network.

    Args:
        net (paddle.nn.Layer||paddle.static.Program): The network which could be a instance of paddle.nn.Layer in
                    dygraph or paddle.static.Program in static graph.
        input_size (list): size of input tensor. Note that the batch_size in argument ``input_size`` only support 1.
        custom_ops (A dict of function, optional): A dictionary which key is the class of specific operation such as
                    paddle.nn.Conv2D and the value is the function used to count the FLOPs of this operation. This
                    argument only work when argument ``net`` is an instance of paddle.nn.Layer. The details could be found
                    in following example code. Default is None.
        print_detail (bool, optional): Whether to print the detail information, like FLOPs per layer, about the net FLOPs.
                    Default is False.

    Returns:
        Int: A number about the FLOPs of total network.

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> import paddle.nn as nn

            >>> class LeNet(nn.Layer):
            ...     def __init__(self, num_classes=10):
            ...         super().__init__()
            ...         self.num_classes = num_classes
            ...         self.features = nn.Sequential(
            ...             nn.Conv2D(1, 6, 3, stride=1, padding=1),
            ...             nn.ReLU(),
            ...             nn.MaxPool2D(2, 2),
            ...             nn.Conv2D(6, 16, 5, stride=1, padding=0),
            ...             nn.ReLU(),
            ...             nn.MaxPool2D(2, 2))
            ...
            ...         if num_classes > 0:
            ...             self.fc = nn.Sequential(
            ...                 nn.Linear(400, 120),
            ...                 nn.Linear(120, 84),
            ...                 nn.Linear(84, 10))
            ...
            ...     def forward(self, inputs):
            ...         x = self.features(inputs)
            ...
            ...         if self.num_classes > 0:
            ...             x = paddle.flatten(x, 1)
            ...             x = self.fc(x)
            ...         return x
            ...
            >>> lenet = LeNet()
            >>> # m is the instance of nn.Layer, x is the input of layer, y is the output of layer.
            >>> def count_leaky_relu(m, x, y):
            ...     x = x[0]
            ...     nelements = x.numel()
            ...     m.total_ops += int(nelements)
            ...
            >>> FLOPs = paddle.flops(lenet,
            ...                      [1, 1, 28, 28],
            ...                      custom_ops= {nn.LeakyReLU: count_leaky_relu},
            ...                      print_detail=True)
            >>> # doctest: +SKIP('numpy print with different version')
            <class 'paddle.nn.layer.conv.Conv2D'>'s flops has been counted
            <class 'paddle.nn.layer.activation.ReLU'>'s flops has been counted
            Cannot find suitable count function for <class 'paddle.nn.layer.pooling.MaxPool2D'>. Treat it as zero FLOPs.
            <class 'paddle.nn.layer.common.Linear'>'s flops has been counted
            +--------------+-----------------+-----------------+--------+--------+
            |  Layer Name  |   Input Shape   |   Output Shape  | Params | Flops  |
            +--------------+-----------------+-----------------+--------+--------+
            |   conv2d_0   |  [1, 1, 28, 28] |  [1, 6, 28, 28] |   60   | 47040  |
            |   re_lu_0    |  [1, 6, 28, 28] |  [1, 6, 28, 28] |   0    |   0    |
            | max_pool2d_0 |  [1, 6, 28, 28] |  [1, 6, 14, 14] |   0    |   0    |
            |   conv2d_1   |  [1, 6, 14, 14] | [1, 16, 10, 10] |  2416  | 241600 |
            |   re_lu_1    | [1, 16, 10, 10] | [1, 16, 10, 10] |   0    |   0    |
            | max_pool2d_1 | [1, 16, 10, 10] |  [1, 16, 5, 5]  |   0    |   0    |
            |   linear_0   |     [1, 400]    |     [1, 120]    | 48120  | 48000  |
            |   linear_1   |     [1, 120]    |     [1, 84]     | 10164  | 10080  |
            |   linear_2   |     [1, 84]     |     [1, 10]     |  850   |  840   |
            +--------------+-----------------+-----------------+--------+--------+
            Total Flops: 347560     Total Params: 61610
            >>> # doctest: -SKIP
            >>> print(FLOPs)
            347560
    )inputsr   r   )r   zKYour model must be an instance of paddle.nn.Layer or paddle.static.Program.)
isinstancer   r   r   forwardpaddlerandndynamic_flopsstaticr   r
   warningswarn)r   r   r   r   _r   s         i/lsinfo/ai/hellotax_ai/data_center/backend/venv/lib/python3.11/site-packages/paddle/hapi/dynamic_flops.pyflopsr'   (   s    p #rx    +3;773;j)):L
 
 
 	
 
C.	/	/ Cl;;;;Y	
 	
 	
 r    c                F   |d         }t          j        | j        j        dd                    }| j        dnd}t          |                                          |j        d         | j        z  |z  |z   z  }| xj        t          t          |                    z  c_        d S Nr      r   )
npprodweightshapebiasr   numel_groups	total_opsabs)mxy
kernel_opsbias_opsr3   s         r&   count_convNdr:      s    	!A+,,JF&qqAHAGGII	
QY+h6I KK3s9~~&&&KKKKr(   c                x    |d         }|                                 }| xj        t          |          z  c_        d S Nr   r1   r3   r   )r5   r6   r7   	nelementss       r&   count_leaky_relur?      s2    	!A		IKK3y>>!KKKKr(   c                    |d         }|                                 }| j        sd|z  }| xj        t          t	          |                    z  c_        d S )Nr   r+   )r1   trainingr3   r4   r   )r5   r6   r7   r>   r3   s        r&   count_bnrB      sM    	!A		I: "	M	KK3s9~~&&&KKKKr(   c                    | j         j        d         }|                                }||z  }| xj        t	          t          |                    z  c_        d S r<   )r.   r/   r1   r3   r4   r   )r5   r6   r7   	total_mulnum_elementsr3   s         r&   count_linearrF      sI    q!I7799LL(IKK3s9~~&&&KKKKr(   c                v    d}|                                 }||z  }| xj        t          |          z  c_        d S )Nr   r=   )r5   r6   r7   r8   rE   r3   s         r&   count_avgpoolrH      s8    J7799L\)IKK3y>>!KKKKr(   c                T   t          j        |d         j        dd                    t          j        |j        dd                    z  }t          j        |          }d}||z   }|                                }||z  }| xj        t          t          |                    z  c_        d S r*   )r,   arrayr/   r-   r1   r3   r4   r   )	r5   r6   r7   kernel	total_add	total_divr8   rE   r3   s	            r&   count_adap_avgpoolrN      s    Xadjn%%!'!""+)>)>>FIIY&J7799L\)IKK3s9~~&&&KKKKr(   c                &    | xj         dz  c_         d S r<   )r3   r5   r6   r7   s      r&   count_zero_opsrQ      s    KK1KKKKr(   c                    d}|                                  D ]}||                                z  }t          t          |                    | j        d<   d S r<   )
parametersr1   r4   r   total_params)r5   r6   r7   rT   ps        r&   count_parametersrV      sT    L\\^^ " "		!C--..AN1r(   c                h   |                      dt          j        |d         j                             t	          |t
          t          f          r5|                      dt          j        |d         j                             d S |                      dt          j        |j                             d S )Ninput_shaper   output_shape)register_bufferr   	to_tensorr/   r   listtuplerP   s      r&   count_io_infor^      s    mV%5adj%A%ABBB!dE]## E	.&*:1Q4:*F*FGGGGG	.&*:17*C*CDDDDDr(   modelr   r   r   c           
        g t                      i fd}| j        }|                                  |                     |           t          j                                        5   | |           d d d            n# 1 swxY w Y   d}d}|                                 D ]}t          t          |
                                                    dk    r5h d                    t          |j                                                            r||j        z  }||j        z  }|r|                                  D ]}	|	                                 t%          g d          }
|                                 D ]\  }}t          t          |
                                                    dk    r9h d                    t          |j                                                            r
|
                    |                                |j                                                                        |j                                                                        t5          |j                  t5          |j                  g           |j                            d           |j                            d           |j                            d           |j                            d           |r|
                                 t;          d	t5          |           d
t5          |                      t5          |          S )Nc                J   t          t          |                                                     dk    rd S |                     dt	          j        dgd                     |                     dt	          j        dgd                     t          |           }d }|v r|         }|vrt          d|            nD|t          v r$t          |         }|vrt          | d           n|vrt          d	| d
           |*| 	                    |          }
                    |           | 	                    t                    }| 	                    t                    }
                    |           
                    |                               |           d S )Nr   r3   r   int64)dtyperT   z'Customize Function has been applied to z's flops has been countedz(Cannot find suitable count function for z. Treat it as zero FLOPs.)lenr\   childrenrZ   r   zerostypeprintregister_hooksregister_forward_post_hookappendrV   r^   add)	r5   m_typeflops_fnflops_handlerparams_handler
io_handlerr   handler_collectiontypes_collections	         r&   	add_hooksz dynamic_flops.<locals>.add_hooks   s   tAJJLL!!""Q&&F	+v|QCw'G'G'GHHH	.&,s'*J*J*JKKKaZ!&)H---HHHIII~%%%f-H---:::;;;---`v```   88BBM%%m444556FGG11-@@
!!.111!!*---V$$$$$r(   r   >   r3   rX   rY   rT   )z
Layer NamezInput ShapezOutput ShapeParamsFlopsr3   rT   rX   rY   zTotal Flops: z     Total Params: )setrA   evalapplyr   	frameworkno_grad	sublayersrd   r\   re   issubset_bufferskeysr3   rT   trainremover	   named_sublayersadd_row	full_namerX   numpytolistrY   r   popprint_tablerh   )r_   r   r   r   rt   rA   r3   rT   r5   handlertablenrr   rs   s     `         @@r&   r!   r!      sx    uu
% % % % % % %> ~H	JJLLL	KK				!	!	#	#  f               IL__ 
+ 
+tAJJLL!!""Q&&
 
 

 (3qz(())
*
*	+ $IAN*L %  HHH E %%'' + +1tAJJLL!!""Q&&
 
 

 (3qz(())
*
*	+ MMKKMMM''))0022N((**1133''$$   JNN;'''JNN>***JNN=)))JNN>*** 	NINN3|;L;LNN   y>>s   -BB	B	)NF)
r   r   r   r   r   r   r   r   r   r   )
r_   r   r   r   r   r   r   r   r   r   )<
__future__r   r#   typingr   r   r,   typing_extensionsr   r   r   'paddle.jit.dy2static.program_translatorr   r
   r	   collections.abcr   r   	paddle.nnr   paddle.staticr   dictrg   r   __annotations____all__r'   r:   r?   rB   rF   rH   rN   rQ   rV   r^   Conv1DConv2DConv3DConv1DTransposeConv2DTransposeConv3DTransposelayernormBatchNorm2D	BatchNormReLUReLU6	LeakyReLULinearDropout	AvgPool1D	AvgPool2D	AvgPool3DAdaptiveAvgPool1DAdaptiveAvgPool2DAdaptiveAvgPool3Dri   r!    r(   r&   <module>r      s   # " " " " " "                  ' ' ' ' ' '        E E E E E E - - - - - - - - H((((((%%%%%%!%d5k8I3F&F!GOGGGG
 *.	g g g g gT' ' '" " "' ' '' ' '" " "' ' '  / / /E E EI|I| I| 	
   HMx L( G^ Hn L" I| J L- L-  L-!" ,#$ ,,' 4 *.	d d d d d d dr(   