
    wi                        d Z ddlmZmZmZ ddlZddlmZmZm	Z	m
Z
 ddlZddlZddlmZ ddlmc mZ ddlmZ  G d dej                  Z G d	 d
ej                  Z	 	 	 	 	 dEdZd Zd Zd Zd Zd Zd Z G d dej                  Z  G d dej                  Z! G d dej                  Z"d Z#	 dFdej        de$de$de%fdZ&de$dej        de
de	ee$e
ej        e$df         f                  f         fd Z'd!d"d#d$d%d&d'd(Z( e)e(*                                          Z+ G d) d*e"          Z, G d+ d,e"          Z- G d- d.e"          Z. G d/ d0ej        j                  Z/ G d1 d2e"          Z0 G d3 d4e"          Z1 G d5 d6e"          Z2 G d7 d8e"          Z3dGd:Z4dGd;Z5dGd<Z6dGd=Z7dHd>Z8dGd?Z9dGd@Z: G dA dBej                  Z; G dC dDej                  Z<dS )Iz
This code is refer from:
https://github.com/PaddlePaddle/PaddleClas/blob/2f36cab604e439b59d1a854df34ece3b10d888e3/ppcls/arch/backbone/legendary_models/pp_hgnet_v2.py
    )absolute_importdivisionprint_functionN)CallableDictListUnion   )DonutSwinModelOutputc                   ,     e Zd Zd fd	Zd Zd Z xZS )IdentityBasedConv1x1r
   c           	         t          t          |                               ||ddd|d           ||z  dk    sJ ||z  }t          j        ||ddf          }t          |          D ]}d||||z  ddf<   t          j        |          | _        | j	        
                    t          j        | j	                             d S )Nr
   r   F)in_channelsout_channelskernel_sizestridepaddinggroups	bias_attr)superr   __init__npzerosrangetorchTensor	id_tensorweight	set_value
zeros_like)selfchannelsr   	input_dimid_valuei	__class__s         /var/www/development/aibuddy-work/election-extract/venv/lib/python3.11/site-packages/rapidocr/networks/backbones/rec_pphgnetv2.pyr   zIdentityBasedConv1x1.__init__'   s    "D))22 ! 	3 	
 	
 	
 & A%%%%&	8Xy!Q788x 	1 	1A/0HQIq!+,,h//e.t{;;<<<<<    c           	      n    | j         | j        z   }t          j        ||d dd| j        | j                  }|S )Nr
   r   )r   r   dilationr   )r   r   Fconv2d	_dilation_groups)r!   inputkernelresults       r'   forwardzIdentityBasedConv1x1.forward:   sF    t~-^<
 
 
 r(   c                      | j         | j        z   S N)r   r   r!   s    r'   get_actual_kernelz&IdentityBasedConv1x1.get_actual_kernelG   s    {T^++r(   r
   )__name__
__module____qualname__r   r2   r6   __classcell__r&   s   @r'   r   r   &   s[        = = = = = =&  , , , , , , ,r(   r   c                        e Zd Zdddej        f fd	Zd Zed             Zed             Z	ed             Z
ed	             Zed
             Z xZS )BNAndPadgh㈵>g?Nc                     t                                                        ||||          | _        || _        || _        d S )N)momentumepsilon)r   r   bn
pad_pixelslast_conv_bias)r!   rC   num_featuresrA   r@   rD   rB   r&   s          r'   r   zBNAndPad.__init__L   sH     	"\HgFFF$,r(   c                 V   |                      |          }| j        dk    r| j         j         }| j        
|| j        z  }| j         j        | j         j        |t          j        | j         j        | j         j	        z             z  z  z   }	 |j
        \  }}}}|                    g d          }	|	                    |d| j        |g          }
t          j        |
||
gd          }|| j        dz  z   }|	                    |d|| j        g          }t          j        |||gd          }|}|S )Nr   r
   r
   r
   rH      dim   )rB   rC   _meanrD   biasr   r   sqrt	_variance_epsilonshapereshapeexpandcat)r!   r/   outputrN   
pad_valuesnchwvaluesw_valuesxh_valuess                r'   r2   zBNAndPad.forwardZ   s-   ?QGM>D".++uz$'"3dg6F"FGGG) J JAq!Q''66F}}aT_a%@AAH	8VX6A>>>ADOa''A}}aQ%@AAH	8Q1q999AFr(   c                     | j         j        S r4   )rB   r   r5   s    r'   r   zBNAndPad.weighto   s    w~r(   c                     | j         j        S r4   )rB   rN   r5   s    r'   rN   zBNAndPad.biass   s    w|r(   c                     | j         j        S r4   )rB   rM   r5   s    r'   rM   zBNAndPad._meanw   s    w}r(   c                     | j         j        S r4   )rB   rP   r5   s    r'   rP   zBNAndPad._variance{   s    w  r(   c                     | j         j        S r4   )rB   rQ   r5   s    r'   rQ   zBNAndPad._epsilon   s    wr(   )r8   r9   r:   nnBatchNorm2dr   r2   propertyr   rN   rM   rP   rQ   r;   r<   s   @r'   r>   r>   K   s        
 >- - - - - -  *   X   X   X ! ! X!     X         r(   r>   r   c                     t          j        | ||||||d|	  	        }t          j        |          }	t          j                    }
|
                    d|           |
                    d|	           |
S )NF)	r   r   r   r   r   r*   r   r   padding_mode)rE   convrB   )re   Conv2drf   
Sequentialadd_sublayer)r   r   r   r   r   r*   r   ri   
conv_layerbn_layerses              r'   conv_bnrq      s     !!
 
 
J ~<888H	BOOFJ'''OOD(###Ir(   c                     |j         }|j        |j        z                                   }| ||z                      g d          z  |j        |j        |z  |z  z
  fS )N)rH   r
   r
   r
   )r   rP   rQ   rO   rS   rN   rM   )r0   rB   gammastds       r'   transI_fusebnru      sa    IE<"+%
+
+
-
-C53;''667
"(U"S(( r(   c                 >    t          |           t          |          fS r4   )sumkernelsbiasess     r'   transII_addbranchr{      s    w<<V$$r(   c                    |dk    rYt          j        ||                     g d                    }||                    g d          z                      d          }ng }g }|                     g d          }	| j        d         |z  }
|j        d         |z  }t          |          D ]}|	d d ||
z  |dz   |
z  d d d d f         }|||z  |dz   |z  d d d d d d f         }|                    t          j        ||                     |                    ||||
z  |dz   |
z                               g d          z                      d                     t          ||          \  }}|||z   fS )Nr
   )r
   r   rI   rL   rG   )r
   rI   rL   r   )	r+   r,   	transposerS   rw   rR   r   appendtransIV_depthconcat)k1b1k2b2r   kb_hatk_slicesb_slicesk1_Tk1_group_widthk2_group_widthg
k1_T_slicek2_slices                  r'   transIII_1x1_kxkr      s   {{HRlll3344bjj///44Y??||LLL))!.!.v 	 	Aaaa^!3q1u6N!NPQPQPQSTSTSTTUJ!n,A/GGAAAqqqPQHOOAHXz::;;;OO^+q1u.FFGOO%  #i..    'x::5ebj=r(   c                 V    t          j        | d          t          j        |          fS )Nr   rJ   )r   rU   rx   s     r'   r   r      s&    9W!$$$ei&7&777r(   c                     | |z  }t          j        | |||f          }d|dz  z  |t          j        |           t          j        t          j        |          |          d d d d f<   |S )N      ?rI   )r   r   r   arangetile)r"   r   r   r#   r   s        r'   
transV_avgr      sr    F"IXy+{CDDAk1n bi2729Y#7#7@@!!!QQQFG Hr(   c                     || j         d         z
  dz  }|| j         d         z
  dz  }t          j        | ||||g          S )NrI   rL   )rR   r+   pad)r0   target_kernel_sizeH_pixels_to_padW_pixels_to_pads       r'   transVI_multiscaler      sN    )FLO;AO)FLO;AO5/?OT  r(   c                   H     e Zd Z	 	 	 	 	 d
 fd	Zd Zd Zd Zd Zd	 Z xZ	S )DiverseBranchBlockr
   NFc	                 J   t                                                       |dz
  dz  }
d}|}|}|}d }|}|| _        |t          j                    | _        nt          j                    | _        || _        || _        || _	        |
|dz  k    sJ |r#t          j
        |||||
||d          | _        nVt          |||||
||          | _        t          j                    | _        ||k     r| j                            dt          j
        ||ddd|d	                     | j                            d
t#          |
|                     | j                            dt          j        ||d                     t          ||d|d|          | _        n0| j                            dt          j        |||
                     | j                            dt          j        |                     |||k     r|nd|z  }t          j                    | _        ||k    r+| j                            dt-          ||                     n4| j                            dt          j
        ||ddd|d	                     | j                            dt#          |
|                     | j                            dt          j
        ||||d|d	                     | j                            dt          j        |                     |r|                                  d S d S )Nr
   rI   Tr   r   r   r   r   r*   r   rN   )r   r   r   r   r   r*   r   rj   r   F)r   r   r   r   r   r   rN   rB   )rC   rE   avg)r   r   r   )r   r   r   r   r   r   avgbnidconv1)r"   r   conv1bn1conv2bn2)r   r   	is_reppedre   Identity	nonlinearReLUr   r   r   rk   dbb_reparamrq   
dbb_originrl   dbb_avgrm   r>   	AvgPool2Ddbb_1x1BatchNorm2Ddbb_1x1_kxkr   single_init)r!   num_channelsnum_filtersfilter_sizer   r   actr   r   kwargsr   r*   r   r   r   internal_channels_1x1_3x3r   r&   s                    r'   r   zDiverseBranchBlock.__init__   s    	?q(""!$(!	"[]]DNNWYYDN&(+***** d	O!y')'!	  	  	 D &')'!  DO =??DL$$))I$/%1$%  !%"     ))(gLQQQ   ))L[QRSSS    ' +!- !!!      ))L$/     L%%gr~l/K/KLLL(0#)L#8#8KKa+o *  "}D(K77 --3[QWXXX     --I$/%>$%  !%"     ))G:STTT   ))	 9!- +!!     ))%1M1MNNN  		 	r(   c                 d   | j         r(|                     |                     |                    S |                     |          }t	          | d          r||                     |          z  }||                     |          z  }||                     |          z  }|                     |          S )Nr   )r   r   r   r   hasattrr   r   r   )r!   inputsouts      r'   r2   zDiverseBranchBlock.forwardk  s    > 	<>>$"2"26":":;;;oof%%4## 	(4<<'''Ct||F###t'''~~c"""r(   c                 *   t          | d          r4t          j        j                            | j        j        j        |           t          | d          r4t          j        j                            | j        j        j        |           t          | d          r4t          j        j                            | j	        j
        j        |           t          | d          r6t          j        j                            | j        j        j        |           d S d S )Nr   r   r   r   )r   r   re   init	constant_r   rB   r   r   r   r   r   r   )r!   gamma_values     r'   
init_gammazDiverseBranchBlock.init_gammav  s    4&& 	LHM##DO$6$={KKK4## 	IHM##DLO$:KHHH4## 	LHM##DL$6$={KKK4'' 	NHM##D$4$8$?MMMMM	N 	Nr(   c                     |                      d           t          | d          r6t          j        j                            | j        j        j        d           d S d S )N        r   r   )	r   r   r   re   r   r   r   rB   r   r5   s    r'   r   zDiverseBranchBlock.single_init  s[    4&& 	DHM##DO$6$=sCCCCC	D 	Dr(   c                    t          | j        j        j        | j        j                  \  }}t          | d          rBt          | j        j        j        | j        j                  \  }}t          || j                  }nd\  }}t          | j	        d          r| j	        j
                                        }n| j	        j        j        }t          || j	        j                  \  }}t          | j	        j        j        | j	        j                  \  }}t!          ||||| j                  \  }	}
t%          | j        | j        | j                  }t          || j        j                  \  }}t          | j        d          rIt          | j        j        j        | j        j                  \  }}t!          ||||| j                  \  }}n||}}t-          |||	|f|||
|f          S )Nr   )r   r   r   )r   rj   )ru   r   rj   r   rB   r   r   r   r   r   r   r6   r   r   r   r   r   r   r   r   r   r   r{   )r!   k_originb_origink_1x1b_1x1k_1x1_kxk_firstb_1x1_kxk_firstk_1x1_kxk_secondb_1x1_kxk_secondk_1x1_kxk_mergedb_1x1_kxk_mergedk_avgk_1x1_avg_secondb_1x1_avg_secondk_1x1_avg_firstb_1x1_avg_firstk_1x1_avg_mergedb_1x1_avg_mergeds                     r'   get_equivalent_kernel_biasz-DiverseBranchBlock.get_equivalent_kernel_bias  s   *O ');
 
( 4## 	 ():)A4<?SSLE5&ud.>??EELE54#Y// 	<".6HHJJOO".4;O+8T-1,
 ,
( .;")4+;+?.
 .
** .>;.
 .
 .
** 4,d.>LL-:5$,BT-U-U**4<(( 	T/<!($,/0 0,O_ 2B  {2 2 2... 2BCS. u.0@Au.0@A
 
 	
r(   c           
         | j         rd S |                                 \  }}t          j        | j        j        j        | j        j        j        | j        j        j        | j        j        j	        | j        j        j
        | j        j        j        | j        j        j        d          | _        | j        j                            |           | j        j                            |           |                     d           |                     d           t%          | d          r|                     d           |                     d           d| _         d S )NTr   r   r   r   r   )r   r   re   rk   r   rj   _in_channels_out_channels_kernel_size_stride_paddingr-   r.   r   r   r   rN   __delattr__r   )r!   r0   rN   s      r'   re_parameterizez"DiverseBranchBlock.re_parameterize  s2   > 	F66889,9-;,9?'/O(1_)3?'/	
 	
 	
 	))&111''---&&&###4## 	(Y''''''r(   )r
   r
   NFF)
r8   r9   r:   r   r2   r   r   r   r   r;   r<   s   @r'   r   r      s         L L L L L L\	# 	# 	#N N ND D D
0
 0
 0
d      r(   r   c                   $     e Zd Z fdZd Z xZS )r   c                 V    t          t          |                                            d S r4   )r   r   r   )r!   r&   s    r'   r   zIdentity.__init__  s%    h&&(((((r(   c                     |S r4    )r!   r   s     r'   r2   zIdentity.forward  s    r(   r8   r9   r:   r   r2   r;   r<   s   @r'   r   r     sG        ) ) ) ) )      r(   r   c                       e Zd Z fdZd Z	 	 	 	 	 ddZddZddZdee	e
e	         f         d	eej        e	gej        f         dee	ej        f         fd
Zde	defdZde	defdZdee	e
e	         f         dee	ej        f         fdZ xZS )TheseusLayerc                     t                                                       i | _        | j        j                                        | _        d | _        d | _         | j	        |i | d S r4   )
r   r   res_dictr&   r8   lowerres_nameprunerquanterinit_net)r!   argsr   r&   s      r'   r   zTheseusLayer.__init__  sc    /5577t&v&&&&&r(   c                 v    d|i}t          | j                  D ]}| j                            |          ||<    |S )Nlogits)listr   pop)r!   layerr/   rV   r   res_keys         r'   _return_dict_hookzTheseusLayer._return_dict_hook  sG    f%DM** 	; 	;G $ 1 1' : :HWr(   Nc                     s|rr|rd }|du rt          |          t          u r|g}t          |t                    rOt	          |          t                    k    st          |          dk     rfd|D             }fd|D             r fd}                     |           |                     |           | 	                    |           d S d S )NTr   c                 F    g | ]}|d k    |t                    k     |S r   len.0valstages_patterns     r'   
<listcomp>z)TheseusLayer.init_net.<locals>.<listcomp>  s>     % % %!88c..A.A(A(A (A(A(Ar(   c                      g | ]
}|         S r   r   r   r%   r   s     r'   r   z)TheseusLayer.init_net.<locals>.<listcomp>
  s    "L"L"L>!#4"L"L"Lr(   c                 2                                    d S r4   )
update_res)r   r/   return_patternsr!   s     r'   update_res_hookz.TheseusLayer.init_net.<locals>.update_res_hook  s    OOO44444r(   )
typeint
isinstancer   maxr   minregister_forward_pre_hookfreeze_befor
stop_after)	r!   r   r  return_stagesr
  r  r   r   r  s	   ```      r'   r   zTheseusLayer.init_net  s^     	@m 	@ %= % $$$"0 M""c))!.-.. M}%%N(;(;;;s=?Q?QTU?U?U% % % %#0% % %M
 #M"L"L"Lm"L"L"L @5 5 5 5 5 5 ..??? #l+++ !OOJ''''' "!r(   c                 J   |r|rd }|du r}t          |t                    r|g}t          |t                    rOt          |          t	                    k    st          |          dk     rfd|D             }fd|D             }|r|                     |           d S d S )NTr   c                 F    g | ]}|d k    |t                    k     |S r   r   r   s     r'   r   z)TheseusLayer.init_res.<locals>.<listcomp>'  s>     ! ! !axxC#n*=*=$=$= $=$=$=r(   c                      g | ]
}|         S r   r   r   s     r'   r   z)TheseusLayer.init_res.<locals>.<listcomp>,  s    HHHQ~a0HHHr(   )r  r  r   r  r   r  r  )r!   r   r  r  s    `  r'   init_reszTheseusLayer.init_res  s     	!} 	! MD  ,OmS)) 	,*OMmT** 	I=!!C$7$7773};M;MPQ;Q;Q! ! ! !,! ! !
 IHHH-HHHO 	-OOO,,,,,	- 	-r(   returnc                 $    d}t          |          )NzTThe function 'replace_sub()' is deprecated, please use 'upgrade_sublayer()' instead.)DeprecationWarning)r!   r   r   msgs       r'   replace_subzTheseusLayer.replace_sub1  s    d %%%r(   layer_name_patternhandle_funcc                 F   t          |t                    s|g}g }|D ]}t          ||           }|st          |          dk    r|d         d         n| }|d         d         }|d         d         }|d         d         }	 |||          }
|	rjt          |	          dk    r=t	          ||          |	d                  }|	dd         D ]
}||         }|
||	d         <   n+|
t	          ||          |	d         <   nt          |||
           |                    |           |S )	a  use 'handle_func' to modify the sub-layer(s) specified by 'layer_name_pattern'.

        Args:
            layer_name_pattern (Union[str, List[str]]): The name of layer to be modified by 'handle_func'.
            handle_func (Callable[[nn.Module, str], nn.Module]): The function to modify target layer specified by 'layer_name_pattern'. The formal params are the layer(nn.Module) and pattern(str) that is (a member of) layer_name_pattern (when layer_name_pattern is List type). And the return is the layer processed.

        Returns:
            Dict[str, nn.Module]: The key is the pattern and corresponding value is the result returned by 'handle_func()'.

        Examples:

            from paddle import nn
            import paddleclas

            def rep_func(layer: nn.Module, pattern: str):
                new_layer = nn.Conv2d(
                    in_channels=layer._in_channels,
                    out_channels=layer._out_channels,
                    kernel_size=5,
                    padding=2
                )
                return new_layer

            net = paddleclas.MobileNetV1()
            res = net.upgrade_sublayer(layer_name_pattern=["blocks[11].depthwise_conv.conv", "blocks[12].depthwise_conv.conv"], handle_func=rep_func)
            print(res)
            # {'blocks[11].depthwise_conv.conv': the corresponding new_layer, 'blocks[12].depthwise_conv.conv': the corresponding new_layer}
        )patternparent_layerr
   r   rH   name
index_listr   )r  r   parse_pattern_strr   getattrsetattrr~   )r!   r  r  hit_layer_pattern_listr  
layer_listsub_layer_parent	sub_layersub_layer_namesub_layer_index_listnew_sub_layersub_layer_indexs               r'   upgrade_sublayerzTheseusLayer.upgrade_sublayer5  s   D ,d33 	6"4!5!#) 	3 	3G*7NNNJ :=j//A:M:Mz"~g66SW"2w/I'^F3N#-b>,#? 'K	7;;M# I+,,q00'./?'P'P,Q/($ ,@"+E M M+;O+L((AN$%9"%=>> & ,n==,Q/  (.-HHH"))'2222%%r(   stop_layer_namec                     t          ||           }|sdS | }|D ]7}|d         |d         }}t          |||          sd| d| d} dS |d         }8dS )	zstop forward and backward after 'stop_layer_name'.

        Args:
            stop_layer_name (str): The name of layer that stop forward and backward after this layer.

        Returns:
            bool: 'True' if successful, 'False' otherwise.
        Fr  r  z5Failed to set the layers that after stop_layer_name('z0') to IdentityLayer. The error layer's name is 'z'.r   T)r  set_identity)r!   r*  r"  r  
layer_dictr  r  r  s           r'   r  zTheseusLayer.stop_afterz  s     '==
 	5$ 	/ 	/J)&1:l3K*DdJ??  Xo  X  X  PT  X  X  Xuu%g.LLtr(   
layer_namec                 f    d }|                      ||          }t          |          dk    rd}dS dS )zfreeze the layer named layer_name and its previous layer.

        Args:
            layer_name (str): The name of layer that would be freezed.

        Returns:
            bool: 'True' if successful, 'False' otherwise.
        c                 P      G  fddt           j                  } |            }|S )Nc                   (     e Zd Z fdZd Z xZS )CTheseusLayer.freeze_befor.<locals>.stop_grad.<locals>.StopGradLayerc                 V    t                                                       | _        d S r4   )r   r   r   )r!   r&   r   s    r'   r   zLTheseusLayer.freeze_befor.<locals>.stop_grad.<locals>.StopGradLayer.__init__  s$    GG$$&&&!&DJJJr(   c                 >    |                      |          }d|_        |S )NT)r   stop_gradientr!   r^   s     r'   r2   zKTheseusLayer.freeze_befor.<locals>.stop_grad.<locals>.StopGradLayer.forward  s    

1A&*AOHr(   r   )r&   r   s   @r'   StopGradLayerr2    sM        ' ' ' ' ' '      r(   r7  )re   Module)r   r  r7  	new_layers   `   r'   	stop_gradz,TheseusLayer.freeze_befor.<locals>.stop_grad  sL          	    &Ir(   r   zAFailed to stop the gradient before the layer named '{layer_name}'FT)r)  r   )r!   r.  r:  resr  s        r'   r
  zTheseusLayer.freeze_befor  sF    	 	 	 ##J	::s88q==UC5tr(   r  c                    i | _          G d dt                    } || j                   }|                     ||          }t          | d          r| j                                         |                     | j                  | _        |S )a  update the result(s) to be returned.

        Args:
            return_patterns (Union[str, List[str]]): The name of layer to return output.

        Returns:
            Dict[str, nn.Module]: The pattern(str) and corresponding layer(nn.Module) that have been set successfully.
        c                       e Zd Zd Zd ZdS )(TheseusLayer.update_res.<locals>.Handlerc                     || _         d S r4   )r   )r!   r   s     r'   r   z1TheseusLayer.update_res.<locals>.Handler.__init__  s     (r(   c                     | j         |_         ||_        t          |d          r|j                                         |                    t                    |_        |S )Nhook_remove_helper)r   r   r   rA  removeregister_forward_post_hooksave_sub_res_hook)r!   r   r  s      r'   __call__z1TheseusLayer.update_res.<locals>.Handler.__call__  s\    !%!(5"677 6,33555+0+K+K%, ,( r(   N)r8   r9   r:   r   rE  r   r(   r'   Handlerr>    s2        ) ) )    r(   rF  )r  rA  )r   objectr)  r   rA  rB  rC  r   )r!   r  rF  r  r!  s        r'   r  zTheseusLayer.update_res  s     	 	 	 	 	f 	 	 	 gdm,,!%!6!6 "7 "
 "
 4-.. 	-#**,,,"&"A"A"#
 #
 &%r(   )NNNNN)NN)r  N)r8   r9   r:   r   r   r   r  r  r	   strr   r   re   r8  r   r)  boolr  r
  r  r;   r<   s   @r'   r   r     sx       ' ' ' ' '   ,( ,( ,( ,(\- - - -,& & & &C&!#tCy.1C& ry#.	9:C& 
c29n		C& C& C& C&J# $    0s t    <*&$S$s)^4*&	c29n	*& *& *& *& *& *& *& *&r(   r   c                 $    || j         | j        <   d S r4   )r   r   )r   r/   rV   s      r'   rD  rD    s    %+EN5>"""r(   r  r.  layer_index_listr  c                 R   d}| j         D ]#}|rt                      | j         |<   ||k    rd}$|rw|ru| j         |         }t          |          D ]X\  }}d}t          |          D ]}|||                  }|j         D ])}	|rt                      | j         |         |	<   !||	k    rd}*Y|S )a  set the layer specified by layer_name and layer_index_list to Identity.

    Args:
        parent_layer (nn.Module): The parent layer of target layer specified by layer_name and layer_index_list.
        layer_name (str): The name of target layer to be set to Identity.
        layer_index_list (str, optional): The index of target layer to be set to Identity in parent_layer. Defaults to None.

    Returns:
        bool: True if successfully, False otherwise.
    FT)_sub_layersr   	enumerater   )
r  r.  rK  r  r%  layer_containernumlayer_indexr%   r(  s
             r'   r,  r,    s     J&2   	7?zzL$^4Z''J &J &&2:> )*: ; ; 		& 		&CJ3ZZ G G"12B12E"F#2#> & & LTJJL,Z8I/11!%J& r(   r  c           	         |                      d          }|sd|  d}dS g }t          |          dk    r%d|d         v r\|d                              d          d         }t          d |d                              d          dd         D                       }n
|d         }d}t          ||d          }|d	| d
|  d}dS |r\|D ]Y}t	          |          dk     s t	          |          t          |          k    rd| d
|  dt          |           d} dS ||         }Z|                    |||d           |dd         }|}t          |          dk    %|S )aq  parse the string type pattern.

    Args:
        pattern (str): The pattern to describe layer.
        parent_layer (nn.Module): The root layer relative to the pattern.

    Returns:
        Union[None, List[Dict[str, Union[nn.Module, str, None]]]]: None if failed. If successfully, the members are layers parsed in order:
                                                                [
                                                                    {"layer": first layer, "name": first layer's name parsed, "index": first layer's index parsed if exist},
                                                                    {"layer": second layer, "name": second layer's name parsed, "index": second layer's index parsed if exist},
                                                                    ...
                                                                ]
    .zThe pattern('z&') is illegal. Please check and retry.Nr   [c              3   L   K   | ]}|                     d           d         V   dS )]r   N)split)r   indexs     r'   	<genexpr>z$parse_pattern_str.<locals>.<genexpr>"  sD       + +(-C  #+ + + + + +r(   r
   zNot found layer named('z') specified in pattern('z').zNot found layer by index('z'). The index should < z	 and > 0.)r   r  r  )rW  r   r   r  r  r~   )	r  r  pattern_listr  r"  target_layer_nametarget_layer_index_listtarget_layertarget_layer_indexs	            r'   r  r    s%   $ ==%%L MgMMMtJ
l

a

,q/!! ,Q 5 5c : :1 =&* + +1=a1F1Fs1K1KABB1O+ + + ' '## !-Q&*#|->EEd,=ddX_dddC4" 	@&= @ @")**Q..#6H2I2IS N N 3 3 a7I  a  adk  a  a  EH  IU  EV  EV  a  a  aC44+,>?%)5 	
 	
 	
 $ABB'#E l

a

H r(   zphttps://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPHGNetV2_B0_ssld_pretrained.pdparamszphttps://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPHGNetV2_B1_ssld_pretrained.pdparamszphttps://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPHGNetV2_B2_ssld_pretrained.pdparamszphttps://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPHGNetV2_B3_ssld_pretrained.pdparamszphttps://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPHGNetV2_B4_ssld_pretrained.pdparamszphttps://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPHGNetV2_B5_ssld_pretrained.pdparamszphttps://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPHGNetV2_B6_ssld_pretrained.pdparams)PPHGNetV2_B0PPHGNetV2_B1PPHGNetV2_B2PPHGNetV2_B3PPHGNetV2_B4PPHGNetV2_B5PPHGNetV2_B6c                   *     e Zd ZdZd fd	Zd Z xZS )LearnableAffineBlocka  
    Create a learnable affine block module. This module can significantly improve accuracy on smaller models.

    Args:
        scale_value (float): The initial value of the scale parameter, default is 1.0.
        bias_value (float): The initial value of the bias parameter, default is 0.0.
        lr_mult (float): The learning rate multiplier, default is 1.0.
        lab_lr (float): The learning rate, default is 0.01.
    r   r   {Gz?c                 P   t                                                       t          j        t          j                            t          j        d                              t          j	                  |                    | _
        |                     d| j
                   t          j        t          j                            t          j        d                              t          j	                  |                    | _        |                     d| j                   d S )Nr
   )r   scalerN   )r   r   r   	Parameterre   r   r   onestofloat32rj  register_parameterrN   )r!   scale_value
bias_valuelr_multlab_lrr&   s        r'   r   zLearnableAffineBlock.__init__  s     _Gejmm..u}==;OO
 

 	444 OGejmm..u}==:NN
 
	 		22222r(   c                 &    | j         |z  | j        z   S r4   )rj  rN   r6  s     r'   r2   zLearnableAffineBlock.forward  s    zA~	))r(   )r   r   r   rh  r8   r9   r:   __doc__r   r2   r;   r<   s   @r'   rg  rg    sV         3 3 3 3 3 38* * * * * * *r(   rg  c                   8     e Zd ZdZ	 	 	 	 	 	 	 d	 fd	Zd Z xZS )
	ConvBNActa  
    ConvBNAct is a combination of convolution and batchnorm layers.

    Args:
        in_channels (int): Number of input channels.
        out_channels (int): Number of output channels.
        kernel_size (int): Size of the convolution kernel. Defaults to 3.
        stride (int): Stride of the convolution. Defaults to 1.
        padding (int/str): Padding or padding type for the convolution. Defaults to 1.
        groups (int): Number of groups for the convolution. Defaults to 1.
        use_act: (bool): Whether to use activation function. Defaults to True.
        use_lab (bool): Whether to use the LAB operation. Defaults to False.
        lr_mult (float): Learning rate multiplier for the layer. Defaults to 1.0.
    rL   r
   TFr   c
           
         t                                                       || _        || _        t	          j        ||||t          |t                    r|n|dz
  dz  |d          | _        t	          j	        |          | _
        | j        r6t	          j                    | _        | j        rt          |	          | _        d S d S d S )Nr
   rI   F)r   r   rN   rr  )r   r   use_actuse_labre   rk   r  rH  rj   rf   rB   r   r   rg  lab)r!   r   r   r   r   r   r   r{  r|  rr  r&   s             r'   r   zConvBNAct.__init__  s     	I)'377SGGkAoRS=S
 
 
	 .
 
 < 	AwyyDH| A/@@@	A 	AA Ar(   c                     |                      |          }|                     |          }| j        r1|                     |          }| j        r|                     |          }|S r4   )rj   rB   r{  r   r|  r}  r6  s     r'   r2   zConvBNAct.forward  sW    IIaLLGGAJJ< 	 A|  HHQKKr(   )rL   r
   r
   r
   TFr   ru  r<   s   @r'   rx  rx    st         & A A A A A A@      r(   rx  c                   .     e Zd ZdZ	 	 d fd	Zd Z xZS )LightConvBNActa  
    LightConvBNAct is a combination of pw and dw layers.

    Args:
        in_channels (int): Number of input channels.
        out_channels (int): Number of output channels.
        kernel_size (int): Size of the depth-wise convolution kernel.
        use_lab (bool): Whether to use the LAB operation. Defaults to False.
        lr_mult (float): Learning rate multiplier for the layer. Defaults to 1.0.
    Fr   c           	          t                                                       t          ||dd||          | _        t          ||||d||          | _        d S )Nr
   F)r   r   r   r{  r|  rr  T)r   r   r   r   r{  r|  rr  )r   r   rx  r   r   )r!   r   r   r   r|  rr  r   r&   s          r'   r   zLightConvBNAct.__init__  st     	#%
 
 

 $%#
 
 



r(   c                 Z    |                      |          }|                     |          }|S r4   )r   r   r6  s     r'   r2   zLightConvBNAct.forward  s%    JJqMMJJqMMr(   )Fr   ru  r<   s   @r'   r  r    s^        	 	  
 
 
 
 
 
8      r(   r  c                   &     e Zd Zd fd	Zd Z xZS )PaddingSameAsPaddleMaxPool2dr
   c                     t                                                       || _        || _        t          j                            ||dd          | _        d S )Nr   T)r   	ceil_mode)r   r   r   r   r   re   	MaxPool2dpool)r!   r   r   r&   s      r'   r   z%PaddingSameAsPaddleMaxPool2d.__init__%  sM    &H&&{FAQU&VV			r(   c                    |j         \  }}}}t          dt          j        || j        z            dz
  | j        z  | j        z   |z
            }t          dt          j        || j        z            dz
  | j        z  | j        z   |z
            }|dz  }|dz  }t          j        j        	                    ||||z
  |||z
  g          }| 
                    |          S )Nr   r
   rI   )rR   r  mathceilr   r   r   re   
functionalr   r  )	r!   r^   _rZ   r[   pad_h_totalpad_w_totalpad_hpad_ws	            r'   r2   z$PaddingSameAsPaddleMaxPool2d.forward+  s    W
1a	!dk/**Q.$+=@PPSTT
 
 	!dk/**Q.$+=@PPSTT
 
 q q H##{U*E;3FG
 
 yy||r(   r7   r   r<   s   @r'   r  r  $  sR        W W W W W W      r(   r  c                   0     e Zd ZdZ	 	 	 d fd	Zd Z xZS )	StemBlockap  
    StemBlock for PP-HGNetV2.

    Args:
        in_channels (int): Number of input channels.
        mid_channels (int): Number of middle channels.
        out_channels (int): Number of output channels.
        use_lab (bool): Whether to use the LAB operation. Defaults to False.
        lr_mult (float): Learning rate multiplier for the layer. Defaults to 1.0.
    Fr   c           	         t                                                       t          ||dd||          | _        t          ||dz  ddd||          | _        t          |dz  |ddd||          | _        t          |dz  |d|rdnd||          | _        t          ||dd||          | _        t          dd          | _	        d S )NrL   rI   r   r   r   r   r|  rr  r
   same)r   r   r   r   r   r|  rr  )r   r   )
r   r   rx  stem1stem2astem2bstem3stem4r  r  )r!   r   mid_channelsr   r|  rr  text_recr&   s          r'   r   zStemBlock.__init__G  s+    	#%
 
 

  $%*
 
 
  $)%
 
 
 $q(% '11a
 
 

 $%
 
 

 1
 
 
			r(   c                 0   |                      |          }|                     |          }|                     |          }|                     |          }t	          j        ||gd          }|                     |          }|                     |          }|S )Nr
   )r  r  r  r  r   rU   r  r  )r!   r^   x2x1s       r'   r2   zStemBlock.forward  sv    JJqMM[[^^[[__YYq\\Ir2h""JJqMMJJqMMr(   )Fr   Fru  r<   s   @r'   r  r  ;  sb        	 	  7
 7
 7
 7
 7
 7
r	 	 	 	 	 	 	r(   r  c                   6     e Zd ZdZ	 	 	 	 	 	 d	 fd	Zd Z xZS )

HGV2_BlockaX  
    HGV2_Block, the basic unit that constitutes the HGV2_Stage.

    Args:
        in_channels (int): Number of input channels.
        mid_channels (int): Number of middle channels.
        out_channels (int): Number of output channels.
        kernel_size (int): Size of the convolution kernel. Defaults to 3.
        layer_num (int): Number of layers in the HGV2 block. Defaults to 6.
        stride (int): Stride of the convolution. Defaults to 1.
        padding (int/str): Padding or padding type for the convolution. Defaults to 1.
        groups (int): Number of groups for the convolution. Defaults to 1.
        use_act (bool): Whether to use activation function. Defaults to True.
        use_lab (bool): Whether to use the LAB operation. Defaults to False.
        lr_mult (float): Learning rate multiplier for the layer. Defaults to 1.0.
    rL      FTr   c
                    t                                                       || _        t          j                    | _        |rdnd}
t          |          D ]@}| j                             t          |
          |dk    r|n||d|||	                     A|||z  z   }t          ||dz  dd||	          | _
        t          |dz  |dd||	          | _        d S )Nr  rx  r   r
   )r   r   r   r   r|  rr  rI   r  )r   r   identityre   
ModuleListlayersr   r~   evalrx  aggregation_squeeze_convaggregation_excitation_conv)r!   r   r  r   r   	layer_numr  light_blockr|  rr  
block_typer%   total_channelsr&   s                r'   r   zHGV2_Block.__init__  s$    	 moo)4E%%+
y!! 
	 
	AK Z  /0Avv<!- +##  	 	 	 	 %y<'??(1&%*)
 )
 )
% ,5$)%,
 ,
 ,
(((r(   c                 $   |}g }|                     |           | j        D ]"} ||          }|                     |           #t          j        |d          }|                     |          }|                     |          }| j        r||z  }|S )Nr
   rJ   )r~   r  r   rU   r  r  r  )r!   r^   r  rV   r   s        r'   r2   zHGV2_Block.forward  s    a[ 	 	EaAMM!If!$$$))!,,,,Q//= 	MAr(   )rL   r  FTFr   ru  r<   s   @r'   r  r    sk         , -
 -
 -
 -
 -
 -
^      r(   r  c                   8     e Zd ZdZ	 	 	 	 	 	 	 d
 fd	Zd	 Z xZS )
HGV2_Stagea  
    HGV2_Stage, the basic unit that constitutes the PPHGNetV2.

    Args:
        in_channels (int): Number of input channels.
        mid_channels (int): Number of middle channels.
        out_channels (int): Number of output channels.
        block_num (int): Number of blocks in the HGV2 stage.
        layer_num (int): Number of layers in the HGV2 block. Defaults to 6.
        is_downsample (bool): Whether to use downsampling operation. Defaults to False.
        light_block (bool): Whether to use light block. Defaults to True.
        kernel_size (int): Size of the convolution kernel. Defaults to 3.
        use_lab (bool, optional): Whether to use the LAB operation. Defaults to False.
        lr_mult (float, optional): Learning rate multiplier for the layer. Defaults to 1.0.
    r  TrL   FrI   r   c                 `   t                                                       || _        | j        rt          ||d|
|d|	|          | _        g }t          |          D ]=}|                    t          |dk    r|n||||||dk    rdnd||	|	  	                   >t          j	        | | _
        d S )NrL   F)r   r   r   r   r   r{  r|  rr  r   T)	r   r  r   r   r  r  r  r|  rr  )r   r   is_downsamplerx  
downsampler   r~   r  re   rl   blocks)r!   r   r  r   	block_numr  r  r  r   r|  r   rr  blocks_listr%   r&   s                 r'   r   zHGV2_Stage.__init__  s     	* 
	''("	 	 	DO y!! 	 	A/0Avv<!-!- +'&'1ffUU$ +##
 
 
    m[1r(   c                 h    | j         r|                     |          }|                     |          }|S r4   )r  r  r  r6  s     r'   r2   zHGV2_Stage.forward  s2     	#""AKKNNr(   )r  TTrL   FrI   r   ru  r<   s   @r'   r  r    sn         , +2 +2 +2 +2 +2 +2Z      r(   r  c            
       L     e Zd ZdZg ddddddg dddd	f
 fd
	Zd Zd Z xZS )	PPHGNetV2ad  
    PPHGNetV2

    Args:
        stage_config (dict): Config for PPHGNetV2 stages. such as the number of channels, stride, etc.
        stem_channels: (list): Number of channels of the stem of the PPHGNetV2.
        use_lab (bool): Whether to use the LAB operation. Defaults to False.
        use_last_conv (bool): Whether to use the last conv layer as the output channel. Defaults to True.
        class_expand (int): Number of channels for the last 1x1 convolutional layer.
        drop_prob (float): Dropout probability for the last 1x1 convolutional layer. Defaults to 0.0.
        class_num (int): The number of classes for the classification layer. Defaults to 1000.
        lr_mult_list (list): Learning rate multiplier for the stages. Defaults to [1.0, 1.0, 1.0, 1.0, 1.0].
    Returns:
        model: nn.Module. Specific PPHGNetV2 model depends on args.
    rL       @   FT   r     )r   r   r   r   r   Nc                 |   t                                                       |	| _        |
| _        || _        || _        || _        || _        ||ng d| _        g | _	        t          |d         |d         |d         ||d         |
          | _        t          j                    | _        t          |          D ]u\  }}||         \	  }}}}}}}}}| j                            t#          ||||||||||||dz                                 || j        v r| j	                            |           v| j        s|d         d         | _	        t          j        d          | _        | j        rpt          j        || j        dddd	          | _        t          j                    | _        | j        rt1                      | _        t          j        |
          | _        t          j        dd          | _        | j        s-t          j        | j        r| j        n|| j                  | _        |                                   d S )N)r   r
   rI   rL   r   r
   rI   )r   r  r   r|  rr  r  rz  stage4F)r   r   r   r   r   rN   )prH   )	start_dimend_dim)!r   r   detr  r|  use_last_convclass_expand	class_numout_indicesr   r  stemre   r  stagesrN  r~   r  AdaptiveAvgPool2davg_poolrk   	last_convr   r   rg  r}  DropoutdropoutFlattenflattenLinearfc_init_weights)r!   stage_configstem_channelsr|  r  r  dropout_probr  lr_mult_listr  r  r  r   r%   r   r   r  r   r  r  r  r   r  r   r&   s                           r'   r   zPPHGNetV2.__init__2  sw    	 *("*5*A;;||| %a(&q)&q) O
 
 
	 mool++ 	7 	7DAq Q
K  !(Q/     D$$$!((666x 	: ,X 6q 9D,Q// 	6Y(!.  DN wyyDH| 2/11:555DLzAr:::x 	i%)%7I!!\ DG
 	r(   c                    |                                  D ]}t          |t          j                  r%t          j                            |j                   At          |t          j                  rIt          j                            |j                   t          j        	                    |j
                   t          |t          j                  r$t          j        	                    |j
                   d S r4   )modulesr  re   rk   r   kaiming_normal_r   rf   ones_zeros_rN   r  )r!   ms     r'   r  zPPHGNetV2._init_weights  s     	' 	'A!RY'' '''1111A00 'ah'''qv&&&&Ary)) 'qv&&&	' 	'r(   c                 T   |                      |          }g }t          | j                  D ]5\  }} ||          }| j        r|| j        v r|                    |           6| j        r|S | j        r6| j        rt          j	        |ddg          }nt          j
        |ddg          }|S )Nr
   (   rL   rI   )r  rN  r  r  r  r~   r  trainingr+   adaptive_avg_pool2d
avg_pool2d)r!   r^   r   r%   stages        r'   r2   zPPHGNetV2.forward  s    IIaLL!$+.. 	 	HAuaAx A!111

18 	J= 	,} ,)!aW55LQF++r(   )r8   r9   r:   rv  r   r  r2   r;   r<   s   @r'   r  r  !  s         & "kk...] ] ] ] ] ]~' ' '      r(   r  Fc                 H    g dg dg dg dd}t          d	g d|dd|}|S )
ag  
    PPHGNetV2_B0
    Args:
        pretrained (bool/str): If `True` load pretrained parameters, `False` otherwise.
                    If str, means the path of the pretrained model.
        use_ssld (bool) Whether using ssld pretrained model when pretrained is True.
    Returns:
        model: nn.Module. Specific `PPHGNetV2_B0` model depends on args.
    )   r  r  r
   FFrL   rL   )r  r     r
   TFrL   rL   )r  r     rI   TT   rL   )r        r
   TTr  rL   stage1stage2stage3r  )rL   r  r  Tr  r  r|  r   r  
pretraineduse_ssldr   r  models        r'   r_  r_    i     655555555777 L  !kkd NT E Lr(   c                 H    g dg dg dg dd}t          d	g d|dd|}|S )
ag  
    PPHGNetV2_B1
    Args:
        pretrained (bool/str): If `True` load pretrained parameters, `False` otherwise.
                    If str, means the path of the pretrained model.
        use_ssld (bool) Whether using ssld pretrained model when pretrained is True.
    Returns:
        model: nn.Module. Specific `PPHGNetV2_B1` model depends on args.
    )r  r  r  r
   FFrL   rL   )r  0   r  r
   TFrL   rL   )r  `   r  rI   TTr  rL   )r     r  r
   TTr  rL   r  rL      r  Tr  r   r  r  s        r'   r`  r`    r  r(   c                 H    g dg dg dg dd}t          d	g d|dd|}|S )
ag  
    PPHGNetV2_B2
    Args:
        pretrained (bool/str): If `True` load pretrained parameters, `False` otherwise.
                    If str, means the path of the pretrained model.
        use_ssld (bool) Whether using ssld pretrained model when pretrained is True.
    Returns:
        model: nn.Module. Specific `PPHGNetV2_B2` model depends on args.
    )r  r  r  r
   FFrL      )r  r    r
   TFrL   r  )r   r     rL   TTr  r  )r  r  i   r
   TTr  r  r  r  Tr  r   r  r  s        r'   ra  ra    si     655555666777 L  !kkd NT E Lr(   c                 H    g dg dg dg dd}t          d	g d|dd|}|S )
ag  
    PPHGNetV2_B3
    Args:
        pretrained (bool/str): If `True` load pretrained parameters, `False` otherwise.
                    If str, means the path of the pretrained model.
        use_ssld (bool) Whether using ssld pretrained model when pretrained is True.
    Returns:
        model: nn.Module. Specific `PPHGNetV2_B3` model depends on args.
    )r  r  r  r
   FFrL   r  )r  r  r  r
   TFrL   r  )r  r  r  rL   TTr  r  )r  r  r  r
   TTr  r  r  r  Tr  r   r  r  s        r'   rb  rb    si     766666777888 L  !kkd NT E Lr(   c                     ddddddddddgg	dd	d
dddddddgg	d
dddddddddgg	ddddddddddgg	d}g dg dg dg dd}t          dg d|r|n|d||d|}|S )ag  
    PPHGNetV2_B4
    Args:
        pretrained (bool/str): If `True` load pretrained parameters, `False` otherwise.
                    If str, means the path of the pretrained model.
        use_ssld (bool) Whether using ssld pretrained model when pretrained is True.
    Returns:
        model: nn.Module. Specific `PPHGNetV2_B4` model depends on args.
    r  r  r
   TFrL   r  rI   r  r  r  r  r  r   r  r  	r  r  r  r
   FFrL   r  rI   	r  r  r  r
   TFrL   r  rI   	r  r  r  rL   TTr  r  rI   	r  r   r  r
   TTr  r  rI   rL   r  r  )r  r  r|  r  r  r   r  )r  r  r  r  r   stage_config_recstage_config_detr  s           r'   rc  rc    s     r341q!f=CD%A1v>T1dD!QA?dAtT1a!Q@  :99999:::;;;   !kk),B%%2B   E Lr(   c                 H    g dg dg dg dd}t          d	g d|dd|}|S )
ag  
    PPHGNetV2_B5
    Args:
        pretrained (bool/str): If `True` load pretrained parameters, `False` otherwise.
                    If str, means the path of the pretrained model.
        use_ssld (bool) Whether using ssld pretrained model when pretrained is True.
    Returns:
        model: nn.Module. Specific `PPHGNetV2_B5` model depends on args.
    )r  r  r  r
   FFrL   r  )r  r  r  rI   TFrL   r  )r  r  r  r  TTr  r  )r  r  r  rI   TTr  r  r  r  Fr  r   r  r  s        r'   rd  rd  1  i     766777777888 L  !kke OU E Lr(   c                 H    g dg dg dg dd}t          d	g d|dd|}|S )
ag  
    PPHGNetV2_B6
    Args:
        pretrained (bool/str): If `True` load pretrained parameters, `False` otherwise.
                    If str, means the path of the pretrained model.
        use_ssld (bool) Whether using ssld pretrained model when pretrained is True.
    Returns:
        model: nn.Module. Specific `PPHGNetV2_B6` model depends on args.
    )r  r  r  rI   FFrL   r  )r  r  r  rL   TFrL   r  )r  r   r  r  TTr  r  )r  r  r  rL   TTr  r  r  rL   r  r  Fr  r   r  r  s        r'   re  re  I  r  r(   c                   *     e Zd ZdZd fd	Zd Z xZS )PPHGNetV2_B4_Formulaa,  
    PPHGNetV2_B4_Formula
    Args:
        in_channels (int): Number of input channels. Default is 3 (for RGB images).
        class_num (int): Number of classes for classification. Default is 1000.
    Returns:
        model: nn.Module. Specific `PPHGNetV2_B4` model with defined architecture.
    rL   r  c                     t                                                       || _        d| _        g dg dg dg dd}t	          g d||d	          | _        d S )
Nr  r  r  r  r  r  r  F)r  r  r  r|  )r   r   r   r   r  
pphgnet_b4r!   r   r  r  r&   s       r'   r   zPPHGNetV2_B4_Formula.__init__k  s    &  >=====>>>???
 
 $%++%	
 
 
r(   c                    | j         r|\  }}}n t          |t                    r	|d         }n|}|j        d         }|dk    rt	          j        |dd          }|                     |          }|j        \  }}}	}
|                    |||	|
z  g                              g d          }t          |d d dd           }| j         r|||fS |S Nr   r
   rL   )repeatsrK   )r   rI   r
   F)last_hidden_statepooler_outputhidden_states
attentionsreshaped_hidden_states)
r  r  r   rR   r   repeat_interleaver  rS   r}   r   )r!   
input_datapixel_valueslabelattention_maskr   pphgnet_b4_outputbrY   rZ   r[   s              r'   r2   zPPHGNetV2_B4_Formula.forward~     = 	*2</L%*d++ *)!})#)!,1 2<PQRRRL OOL99&,
1a-55q!QUmDDNNII
 
 1/#'
 
 
 = 	%$e^;;$$r(   rL   r  ru  r<   s   @r'   r  r  a  V         
 
 
 
 
 
&% % % % % % %r(   r  c                   *     e Zd ZdZd fd	Zd Z xZS )PPHGNetV2_B6_Formulaa,  
    PPHGNetV2_B6_Formula
    Args:
        in_channels (int): Number of input channels. Default is 3 (for RGB images).
        class_num (int): Number of classes for classification. Default is 1000.
    Returns:
        model: nn.Module. Specific `PPHGNetV2_B6` model with defined architecture.
    rL   r  c                     t                                                       || _        d| _        g dg dg dg dd}t	          g d||d	          | _        d S )
Nr  )	r  r  r  rI   FFrL   r  rI   )	r  r  r  rL   TFrL   r  rI   )	r  r   r  r  TTr  r  rI   )	r  r  r  rL   TTr  r  rI   r  r  F)r  r  r  r|  )r   r   r   r   r  
pphgnet_b6r  s       r'   r   zPPHGNetV2_B6_Formula.__init__  s    &  >==>>>>>>???
 
 $%++%	
 
 
r(   c                    | j         r|\  }}}n t          |t                    r	|d         }n|}|j        d         }|dk    rt	          j        |dd          }|                     |          }|j        \  }}}	}
|                    |||	|
z  g                              g d          }t          |d d dd           }| j         r|||fS |S r  )
r  r  r   rR   r   r  r)  rS   r}   r   )r!   r  r  r  r   r   pphgnet_b6_outputr"  rY   rZ   r[   s              r'   r2   zPPHGNetV2_B6_Formula.forward  r#  r(   r$  ru  r<   s   @r'   r'  r'    r%  r(   r'  )r
   r   r
   r
   r   r4   )FF)FFFF)=rv  
__future__r   r   r   r  typingr   r   r   r	   numpyr   r   torch.nnre   torch.nn.functionalr  r+   rec_donut_swinr   rk   r   r8  r>   rq   ru   r{   r   r   r   r   r   r   r   rD  rH  rI  r,  r  
MODEL_URLSr   keys__all__rg  rx  r  r  r  r  r  r  r_  r`  ra  rb  rc  rd  re  r  r'  r   r(   r'   <module>r5     s   
 A @ @ @ @ @ @ @ @ @  / . . . . . . . . . . .                     1 0 0 0 0 0", ", ", ", ",29 ", ", ",J6  6  6  6  6 ry 6  6  6 z    8  % % %  48 8 8    s s s s s s s sl    ry   @& @& @& @& @&29 @& @& @&F, , ,
 GK# #)#),#@C#	# # # #L<< "	<
4d3bid&: ;;<==>< < < <t G G G G G G G 
 $z  
!
!(* (* (* (* (*< (* (* (*V7 7 7 7 7 7 7 7t+ + + + +\ + + +\    58?   .N N N N N N N NbM M M M M M M M`B B B B B B B BJI I I I I I I IX   0   0   0   0! ! ! !H   0   07% 7% 7% 7% 7%29 7% 7% 7%t7% 7% 7% 7% 7%29 7% 7% 7% 7% 7%r(   