
    sg$9                      d Z ddlmZ ddlZddlmZ ddlmZmZm	Z	 ddl
ZddlZddlmZ ddlmZmZmZmZmZmZ dd	lmZmZmZmZmZmZmZmZm Z m!Z!m"Z" dd
l#m$Z$m%Z%m&Z& ddl'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z- ddl.m/Z/  e,j`                  e1      Z2dZ3dZ4 G d de jj                  jl                        Z7 G d d      Z8d Z9 G d de jj                  jl                        Z: G d de jj                  jl                        Z; G d de jj                  jl                        Z< G d de jj                  jl                        Z=dHdZ> G d de jj                  jl                        Z?e! G d  d!e jj                  jl                               Z@e! G d" d#e jj                  jl                               ZA G d$ d%e jj                  jl                        ZB G d& d'e jj                  jl                        ZC G d( d)e jj                  jl                        ZD G d* d+e      ZEe G d, d-e(             ZFd.ZGd/ZH e*d0eG       G d1 d2eE             ZI e*d3eG       G d4 d5eE             ZJ e*d6eG       G d7 d8eE             ZK e*d9eG       G d: d;eEe             ZL e*d<eG       G d= d>eEe             ZM e*d?eG       G d@ dAeEe             ZN e*dBeG       G dC dDeEe             ZO e*dEeG       G dF dGeEe             ZPy)IzTF 2.0 Funnel model.    )annotationsN)	dataclass)OptionalTupleUnion   )get_tf_activation)TFBaseModelOutputTFMaskedLMOutputTFMultipleChoiceModelOutputTFQuestionAnsweringModelOutputTFSequenceClassifierOutputTFTokenClassifierOutput)TFMaskedLanguageModelingLossTFModelInputTypeTFMultipleChoiceLossTFPreTrainedModelTFQuestionAnsweringLossTFSequenceClassificationLossTFTokenClassificationLossget_initializerkeraskeras_serializableunpack_inputs)check_embeddings_within_bounds
shape_liststable_softmax)ModelOutputadd_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )FunnelConfigr%   g    .Ac                  2     e Zd ZdZ fdZddZddZ xZS )TFFunnelEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                P   t        |   di | || _        |j                  | _        |j                  dn|j                  | _        t
        j                  j                  |j                  d      | _	        t
        j                  j                  |j                        | _        y )N      ?
layer_normepsilonname)rate )super__init__confighidden_sizeinitializer_stdr   layersLayerNormalizationlayer_norm_eps	LayerNormDropouthidden_dropoutdropoutselfr2   kwargs	__class__s      `/var/www/html/venv/lib/python3.12/site-packages/transformers/models/funnel/modeling_tf_funnel.pyr1   zTFFunnelEmbeddings.__init__G   s    "6"!--&,&<&<&Ds&J`J`88AVAV]i8j||++1F1F+G    c                   t        j                  d      5  | j                  d| j                  j                  | j
                  gt        | j                              | _        d d d        | j                  ry d| _	        t        | dd       et        j                  | j                  j                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   xY w# 1 sw Y   y xY w)Nword_embeddingsweight)initializer_range)r-   shapeinitializerTr8   )tf
name_scope
add_weightr2   
vocab_sizer3   r   r4   rD   builtgetattrr8   r-   buildd_modelr=   input_shapes     r@   rN   zTFFunnelEmbeddings.buildQ   s    ]],- 	//{{--t/?/?@+d>R>RS * DK	 ::
4d+7t~~223 H$$dD$++2E2E%FGH H 8	 	H Hs   AC363C?3C<?Dc                    ||J ||J |@t        || j                  j                         t        j                  | j
                  |      }| j                  |      }| j                  ||      }|S )z
        Applies embedding based on inputs tensor.

        Returns:
            final_embeddings (`tf.Tensor`): output embedding tensor.
        )inputs)rS   training)r   r2   rK   rH   gatherrD   r8   r;   )r=   	input_idsinputs_embedsrT   final_embeddingss        r@   callzTFFunnelEmbeddings.call`   s     %-*?@@)m.GHH *9dkk6L6LMIIdkk9=M>>>?<</?(<SrA   NNNF)__name__
__module____qualname____doc__r1   rN   rY   __classcell__r?   s   @r@   r'   r'   D   s    QHH rA   r'   c                  d    e Zd ZU dZdZded<   d ZddZd Zdd	Z	d
 Z
ddZd ZddZd Zd Zy)TFFunnelAttentionStructurez@
    Contains helpers for `TFFunnelRelMultiheadAttention `.
       intcls_token_type_idc                   |j                   | _         |j                  | _        |j                  | _        |j                  | _        |j                  | _        |j
                  | _        |j                  | _        t        j                  j                  |j                        | _        t        j                  j                  |j                        | _        d | _        y rZ   )rO   attention_type
num_blocksseparate_clstruncate_seqpool_q_onlypooling_typer   r5   r9   r:   sin_dropoutcos_dropoutpooling_mult)r=   r2   s     r@   r1   z#TFFunnelAttentionStructure.__init__{   s    ~~$33 ++"//"//!--"// <<//0E0EF <<//0E0EF !rA   Nc                8   d| _         t        |      d   x| _        }| j                  ||      }|| j	                  |      nd}| j
                  rCt        j                  t        j                  |dz
  |dz
  g|j                        ddgddgg      nd}||||fS )zCReturns the attention inputs associated to the inputs of the model.r$   rT   Ndtyper   )
rp   r   seq_lenget_position_embedstoken_type_ids_to_matrj   rH   padonesrt   )	r=   rW   attention_masktoken_type_idsrT   ru   position_embedstoken_type_matcls_masks	            r@   init_attention_inputsz0TFFunnelAttentionStructure.init_attention_inputs   s     !+M!:1!==w227X2NGUGa33NCgk    FF277GaK15]=P=PQUVXYTZ]^`a\bScd 	
  JJrA   c                   t        j                  t        j                  |d      t        j                  |d            }t        j                  |t        j                  | j                  g|j
                              }t        j                  t        j                  |d      t        j                  |d            }t        j                  ||      S )z-Convert `token_type_ids` to `token_type_mat`.rs   )rH   equalexpand_dimsconstantrf   rt   
logical_or)r=   r{   r}   cls_idscls_mats        r@   rw   z0TFFunnelAttentionStructure.token_type_ids_to_mat   s    ".."DbnnUcegFhi((>2;;8N8N7OWeWkWk+lm--w ;R^^GUW=XY}}Wn55rA   c                   | j                   dk(  r%t        j                  d|d      }t        j                  d| j                  dz  d      }dd|| j                  dz  z  z  z  }t        j                  d||      }t        j
                  |      }| j                  ||      }t        j                  |      }	| j                  |	|      }
t        j                  ||gd	
      }t        j                  |	|gd	
      }t        j                  |
|
gd	
      }t        j                  | |	gd	
      }||||fS t        j                  d| j                  dz  d      }dd|| j                  dz  z  z  z  }t        j                  | dz  |dz  d      }|t        j                  d      z  }t        j                  d||      }| j                  t        j
                  |      |      }| j                  t        j                  |      |      }	t        j                  ||	gd	
      }t        j                  d|      }|}g }t        d| j                        D ]-  }t        j                  dgd      }|dk7  rm| j                  ||      }d|dz
  z  }| j                  |||d      }t        j                  ||j                         }||z   }t        j"                  ||d
      }|}d|z  }| j                  ||      }t        j                  ||j                         }||z   }t        j$                  j'                  |t        j(                  |      d          t        j"                  ||d
      }|j+                  ||g       0 |S )a  
        Create and cache inputs related to relative position encoding. Those are very different depending on whether we
        are using the factorized or the relative shift attention:

        For the factorized attention, it returns the matrices (phi, pi, psi, omega) used in the paper, appendix A.2.2,
        final formula.

        For the relative shift attention, it returns all possible vectors R used in the paper, appendix A.2.1, final
        formula.

        Paper link: https://arxiv.org/abs/2006.03236
        
factorizedr   r)   rd   r$   i'  zi,d->idrr   r   axisg      )value)shiftrs   )rh   rH   rangerO   einsumsinrn   cosro   concatr   ri   fillstride_pool_posrelative_poscastrt   rU   	debuggingassert_lessrF   append)r=   ru   rT   pos_seqfreq_seqinv_freqsinusoid	sin_embedsin_embed_d	cos_embedcos_embed_dphipsipiomega
rel_pos_idzero_offset	pos_embedpos
pooled_posposition_embeds_listblock_indexposition_embeds_poolingstriderel_posposition_embeds_no_poolings                             r@   rv   z.TFFunnelAttentionStructure.get_position_embeds   sD    ,. hhq'3/Gxx4<<1#4c:HEh$,,!2C&DEFHyyGX>Hx(I**9x*HKx(I**9x*HK))[+6R@C))Y	2<CK5B?BII	z95B?ES%(( xx4<<1#4c:HEh$,,!2C&DEFH7(Q,!SAJ!BKKN2KyyJAH(()9H(MI(()9H(MI		9i"8rBI((1g&CJ#% $Q8 !c +-''1#T*B'!#!%!5!5c;!GJ ;?3F"//VZq/QG !ggg[5F5FGG%3G.0ii	7QR.S+ !K++C8 '''1B1BC!K/(("((92Ea2HI-/YYy'PQ-R*$++-GI`,abC!cD ('rA   c                    | j                   r]t        j                  d|z   dz   g|j                        }| j                  r|dd n|dd }t        j
                  ||ddd   gd      S |ddd   S )zc
        Pool `pos_id` while keeping the cls token separate (if `self.separate_cls=True`).
        rd   r$   rs   r   Nr   )rj   rH   r   rt   rk   r   )r=   pos_idr   cls_pospooled_pos_ids        r@   r   z*TFFunnelAttentionStructure.stride_pool_pos   sz     
 kkQ^#4q#8"9NG,0,=,=F1RL6!":M99g}SqS'9:A>>#A#;rA   c                    ||}|d   |d   z
  }|t        |      d   z  }|||z  z   }|d   |d   z
  }t        j                  ||dz
  |       S )zV
        Build the relative positional vector between `pos` and `pooled_pos`.
        r   r   r$   )r   rH   r   )	r=   r   r   r   r   	ref_point
num_removemax_distmin_dists	            r@   r   z'TFFunnelAttentionStructure.relative_pos  so     JqMCF*	Z
3A66
zF22a=3r7*xx(Q,88rA   c                    |yt        t        t        f      rD ]  } j                  ||      } |S t        |t        t        f      r t	        |       fd|D              S t        t        |            z   j                  r j                  rt        ddd      nt        ddd      }t        d      gz  |gz   } j                  r8t        d      gz  t        dd      gz   }t        j                  ||   |g      }||   S )zT
        Perform pooling by stride slicing the tensor along the given axis.
        Nc              3  B   K   | ]  }j                  |        y wrZ   )stride_pool).0xr   r=   s     r@   	<genexpr>z9TFFunnelAttentionStructure.stride_pool.<locals>.<genexpr>   s     Ja 0 0D 9Js   r   rd   r$   )
isinstancelisttupler   typelenr   rj   rk   slicerH   r   )r=   tensorr   ax
axis_slice	enc_slice	cls_slices   ` `    r@   r   z&TFFunnelAttentionStructure.stride_pool  s    > dT5M* 6))&"56M fudm,4<J6JJJ 	Jv&''+/+<+<ARARU4Q'X]^bdhjkXl
4[MD(J<7	t,dA/??IYYy 16:DAFi  rA   c                    yt        t        t        f      r t               fdD              S  j                  r; j
                  rddddf   n}t        j                  ddddf   |gd      t        t                    }|dk(  rdddddf   dk(  r%t        j                  j                  dd	
      nadk(  r%t        j                  j                  dd	
      n7dk(  r't        j                  j                   dd	
       nt        d      |dk(  rt        j                  d      S S )z3Apply 1D pooling to a tensor of size [B x T (x H)].Nc              3  F   K   | ]  }j                           yw))moder   N)pool_tensor)r   r   r   r=   r   r   s     r@   r   z9TFFunnelAttentionStructure.pool_tensor.<locals>.<genexpr>3  s$     cWX 0 0d6 0 Rcs   !r   r$   r   rd   meanNWCSAME)stridesdata_formatpaddingmaxminz0The supported modes are 'mean', 'max' and 'min'.)r   r   r   r   rj   rk   rH   r   r   r   nn
avg_pool1d
max_pool1dNotImplementedErrorsqueeze)r=   r   r   r   suffixndims   ````  r@   r   z&TFFunnelAttentionStructure.pool_tensor,  sC   > fudm,4<c\bccc'+'8'8VAssF^fFYYq"1"uv6Q?F:f%&19Aq$J'F6>UU%%fffRWag%hFU]UU%%fffRWag%hFU]ee&&wTYci&jjF%&XYY(,	rzz&!$=v=rA   c                0   |\  }}}}| j                   rl| j                  dk(  r| j                  |dd d      |dd z   }| j                  |d      }| j                  |d      }| j                  || j                        }n| xj
                  dz  c_        | j                  dk(  r| j                  |d      }| j                  |ddg      }| j                  |ddg      }| j                  |d      }| j                  || j                        }||||f}||fS )zTPool `output` and the proper parts of `attention_inputs` before the attention layer.r   Nrd   r   r$   r   r   )rl   rh   r   r   rm   rp   )r=   outputattention_inputsr|   r}   rz   r~   s          r@   pre_attention_poolingz0TFFunnelAttentionStructure.pre_attention_poolingH  s5   DTA""l2"&"2"2?2A3F"J_]^]_M`"`!--na@N''!4H%%f43D3D%EF"""l2"&"2"2?A"F!--nq!fEN''1a&9H!--n5-IN%%f43D3D%EF+^^XV'''rA   c                $   |\  }}}}| j                   rv| xj                  dz  c_        | j                  dk(  r|dd | j                  |dd d      z   }| j                  |d      }| j                  |d      }| j	                  |d      }||||f}|S )zFPool the proper parts of `attention_inputs` after the attention layer.rd   r   Nr   r$   r   r   )rl   rp   rh   r   r   )r=   r   r|   r}   rz   r~   s         r@   post_attention_poolingz1TFFunnelAttentionStructure.post_attention_pooling\  s    DTA"""l2"1"1"58H8HYZY[I\^_8`"`!--na@N''!4H!--n5-IN+^^XVrA   r[   F)Nr$   )r   rd   )r\   r]   r^   r_   rf   __annotations__r1   r   rw   rv   r   r   r   r   r   r   r/   rA   r@   rc   rc   t   sI     s!K6Q(f9!6>8(( rA   rc   c                    t        |       \  }}}}t        j                  | ||||g      } | d d d d |d d d f   } t        j                  | |||||z
  g      } | dd |f   } | S )N.)r   rH   reshape)positional_attncontext_lenr   
batch_sizen_headru   max_rel_lens          r@   _relative_shift_gatherr   j  s~    /9//J,J jj:v{T[2\]O%aEFAo6Ojj:vwP[^cPc2deO%c<K<&78OrA   c                  >     e Zd Z fdZddZddZddZddZ xZS )TFFunnelRelMultiheadAttentionc                   t        |   di | |j                  | _        |j                  x| _        }|j                  x| _        }|j
                  x| _        }|j                  | _        || _        t        j                  j                  |j                        | _        t        j                  j                  |j                        | _        t        |j                        }t        j                  j                  ||z  d|d      | _        t        j                  j                  ||z  |d      | _        t        j                  j                  ||z  |d      | _        t        j                  j                  ||d      | _        t        j                  j'                  |j(                  d	      | _        d
|dz  z  | _        y )NFq_head)use_biaskernel_initializerr-   k_headr   r-   v_head	post_projr*   r+   r)   g      ?r/   )r0   r1   rh   r   d_headrO   rE   r   r   r5   r9   r:   attention_dropoutr   Denser   r   r   r   r6   r7   r*   scale)	r=   r2   r   r>   r   r   rO   rG   r?   s	           r@   r1   z&TFFunnelRelMultiheadAttention.__init__{  sp   "6"$33%}},f%}},f!'/w!'!9!9&#ll2263H3HI!&!5!5f6N6N!O%f&>&>?ll((VOeRZ ) 
 ll((&[_g(hll((&[_g(h++GZe+f,,99&BWBW^j9kFCK(
rA   c                   | j                   | j                  | j                  }}}t        | j                        }| j                  ||f|dd      | _        | j                  ||f|dd      | _        | j                  |||f|dd      | _        | j                  ||f|dd      | _	        | j                  d||f|dd      | _
        | j                  ry d| _        t        | d	d       Pt        j                  | j                  j                         5  | j                  j#                  d d |g       d d d        t        | d
d       Pt        j                  | j$                  j                         5  | j$                  j#                  d d |g       d d d        t        | dd       Pt        j                  | j&                  j                         5  | j&                  j#                  d d |g       d d d        t        | dd       St        j                  | j(                  j                         5  | j(                  j#                  d d ||z  g       d d d        t        | dd       Qt        j                  | j*                  j                         5  | j*                  j#                  d d |g       d d d        y y # 1 sw Y   xY w# 1 sw Y   3xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   y xY w)NTr_w_biasrF   rG   	trainabler-   r_r_biasr_kernelr_s_biasrd   	seg_embedr   r   r   r   r*   )r   r   rO   r   rE   rJ   r   r  r  r  r  rL   rM   rH   rI   r   r-   rN   r   r   r   r*   )r=   rQ   r   r   rO   rG   s         r@   rN   z#TFFunnelRelMultiheadAttention.build  s   "&++t{{DLL%d&<&<=6"tR\ ( 
 6"tR\ ( 
 FF+PT[e ( 
 6"tR\ ( 
 ff%;$U` ) 
 ::
44(4t{{//0 9!!4w"78944(4t{{//0 9!!4w"78944(4t{{//0 9!!4w"7894d+7t~~223 D$$dD&6/%BCD4t,8t334 =%%tT7&;<= = 99 99 99 9D D= =s<   J2/J?K)"K	K$2J<?K	KK!$K-c                   | j                   dk(  r|\  }}}}| j                  | j                  z  }	| j                  }
t	        j
                  d||	z   |
      }||dddf   z  }||dddf   z  }t	        j
                  d||      t	        j
                  d||      z   }nt        |      d   |k7  rd}|| j                     d   }nd}|| j                     d   }| j                  | j                  z  }| j                  }
t	        j
                  d||
      }t	        j
                  d	||z   |      }t        |||      }|||z  }|S )
z5Relative attention score for the positional encodingsr   zbinh,dnh->bindNzbind,jd->bnijr$   rd   r   ztd,dnh->tnhzbinh,tnh->bnit)	rh   r  r   r  rH   r   r   r   r   )r=   r|   r   r   r~   r   r   r   r   uw_rq_r_attentionq_r_attention_1q_r_attention_2r   r   rvr_heads                      r@   relative_positional_attentionz;TFFunnelRelMultiheadAttention.relative_positional_attention  s\    ,. #2CS%

*A--C II&6
CHM+c!T'l:O+bDk9O !ii#NQSQZQZ%R O &!!$3#D$4$45a8#D$4$45a8

*A--C YY}a5F ii(8&1*fMO4_kSXYOx'OrA   c                   |yt        |      \  }}}| j                  | j                  z  }t        j                  d||z   | j
                        }t        j                  |dddf   dt        |      d   ddg      }t        j                  |dd      \  }	}
t        j                  |t        j                  |
ddd|g      t        j                  |	ddd|g            }|||z  }|S )z/Relative attention score for the token_type_idsNr   zbind,snd->bnisr$   rd   r   r   )	r   r  r   rH   r   r  tilesplitwhere)r=   r}   r   r~   r   ru   r   r  token_type_biasdiff_token_typesame_token_typetoken_type_attns               r@   relative_token_type_attentionz;TFFunnelRelMultiheadAttention.relative_token_type_attention  s    !+5n+E(
G[ ==4::- ))$4fx6GX4!81j>PQR>SUVXY:Z[ ,.88OQR+P(((GGOaA{%;<GGOaA{%;<
 x'OrA   c           	        |\  }}}	}
t        |      \  }}}t        |      d   }| j                  | j                  }}t        j                  | j                  |      ||||g      }t        j                  | j                  |      ||||g      }t        j                  | j                  |      ||||g      }|| j                  z  }| j                  | j                  z  }t        j                  d||z   |      }| j                  ||||
      }| j                  |||
      }||z   |z   }|	8t        j                  |	|j                        }	|t        d|	d d d d f   z
  z  z
  }t!        |d      }| j#                  ||      }t        j                  d||      }| j%                  t        j                  |||||z  g            }| j'                  ||      }| j)                  ||z         }|r||fS |fS )Nr$   zbind,bjnd->bnijrs   r   r   rr   zbnij,bjnd->bind)r   r   r   rH   r   r   r   r   r   r   r   r  r  r   rt   INFr   r   r   r:   r*   )r=   querykeyr   r   output_attentionsrT   r|   r}   rz   r~   r   ru   _r   r   r   r   r   r   r   content_scorer   r  
attn_score	attn_probattn_vecattn_outr   s                                r@   rY   z"TFFunnelRelMultiheadAttention.call  s    EUA!+E!2
GQ oa(dkk DKK.Wff0UVDKK,z;PV.WXDKK.[&RX0YZ$**$==4::-		"3Vh5FO<<_fVackl<<^VU]^ #_4F
 %WW^:;K;KLN#sa.D$2O.O'PQJ #:B7	**9x*H	 99.	6B >>"**X
GVV\_7]"^_&&x(&C!12&7	"FfYFrA   rZ   FF)	r\   r]   r^   r1   rN   r  r  rY   r`   ra   s   @r@   r   r   z  s    )0%=N,\6+GrA   r   c                  .     e Zd Z fdZddZddZ xZS )TFFunnelPositionwiseFFNc                l   t        |   di | t        |j                        }t        j
                  j                  |j                  |d      | _        t        |j                        | _        t        j
                  j                  |j                        | _        t        j
                  j                  |j                  |d      | _        t        j
                  j                  |j                         | _        t        j
                  j%                  |j&                  d      | _        || _        y )Nlinear_1r   linear_2r*   r+   r/   )r0   r1   r   rE   r   r5   r   d_innerr(  r	   
hidden_actactivation_functionr9   activation_dropoutrO   r)  r:   r;   r6   r7   r*   r2   r=   r2   r>   rG   r?   s       r@   r1   z TFFunnelPositionwiseFFN.__init__2  s    "6"%f&>&>?**6>>k`j*k#4V5F5F#G "',,"6"6v7P7P"Q**6>>k`j*k||++F,A,AB,,99&BWBW^j9krA   c                    | j                  |      }| j                  |      }| j                  ||      }| j                  |      }| j	                  ||      }| j                  ||z         S Nrr   )r(  r,  r-  r)  r;   r*   )r=   hiddenrT   hs       r@   rY   zTFFunnelPositionwiseFFN.call=  sh    MM&!$$Q'##A#9MM!LLXL.vz**rA   c                   | j                   ry d| _         t        | dd       dt        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        t        | dd       dt        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   y xY w)NTr(  r)  r*   )rL   rM   rH   rI   r(  r-   rN   r2   rO   r)  r*  r*   rP   s     r@   rN   zTFFunnelPositionwiseFFN.buildE  sA   ::
4T*6t}}112 G##T41D1D$EFG4T*6t}}112 G##T41D1D$EFG4t,8t334 I%%tT4;;3F3F&GHI I 9G GG GI Is$   3E*<3E6-3F*E36E?Fr   rZ   r\   r]   r^   r1   rY   rN   r`   ra   s   @r@   r&  r&  1  s    	+IrA   r&  c                  .     e Zd Z fdZddZddZ xZS )TFFunnelLayerc                n    t        |   di | t        ||d      | _        t	        |d      | _        y )N	attentionr-   ffnr/   )r0   r1   r   r8  r&  r:  )r=   r2   r   r>   r?   s       r@   r1   zTFFunnelLayer.__init__U  s2    "6"6v{Q\]*6>rA   c                t    | j                  ||||||      }| j                  |d   |      }|r||d   fS |fS )Nr  rT   r   rr   r$   )r8  r:  )	r=   r  r  r   r   r  rT   attnr   s	            r@   rY   zTFFunnelLayer.callZ  sU    ~~3/CT_g  
 $q'H5$5Q DF9DrA   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   exY w# 1 sw Y   y xY w)NTr8  r:  )rL   rM   rH   rI   r8  r-   rN   r:  rP   s     r@   rN   zTFFunnelLayer.builda  s    ::
4d+7t~~223 +$$T*+4%1txx}}- %t$% % 2+ +% %   C%CCC r$  rZ   r4  ra   s   @r@   r6  r6  T  s    ?
E	%rA   r6  c                  :     e Zd Z fdZ	 	 	 	 	 	 ddZddZ xZS )TFFunnelEncoderc                r   t        |   di | |j                  | _        |j                  | _        |j                  | _        t        |      | _        t        |j                        D cg c]0  \  }}t        |      D cg c]  }t        ||d| d|        c}2 c}}}| _        y c c}w c c}}}w )Nz	blocks_._z_._r9  r/   )r0   r1   rj   rl   block_repeatsrc   attention_structure	enumerateblock_sizesr   r6  blocks)r=   r2   r>   r   
block_sizeir?   s         r@   r1   zTFFunnelEncoder.__init__n  s    "6""//!--#11#=f#E  ,5V5G5G+H
 
'Z `eeo_pqZ[]6;ySQRPS5TUq
q
s   -B2B-B2-B2c                   | j                   j                  ||||      }|}	|r|fnd }
|rdnd }t        | j                        D ]  \  }}t	        |	      d   | j
                  rdndkD  }|xr |dkD  }t        j                  t	        |	            }|r| j                   j                  |	|      \  }}t        |      D ]  \  }}t        | j                  |         D ]r  }|dk(  xr	 |dk(  xr |}|r|}| j                  r|	n|x}}n|	x}x}} |||||||      }|d   }	|r| j                   j                  |      }|r||dd  z   }|sm|
|	fz   }
t   |st        d |	|
|fD              S t        |	|
|      S )	Nrz   r{   rT   r/   r$   rd   r   r<  c              3  &   K   | ]	  }||  y wrZ   r/   r   r  s     r@   r   z'TFFunnelEncoder.call.<locals>.<genexpr>       aqSTS`a   last_hidden_statehidden_states
attentions)rD  r   rE  rG  r   rj   rH   zerosr   r   rC  rl   r   r   r
   )r=   rW   rz   r{   r  output_hidden_statesreturn_dictrT   r   r1  all_hidden_statesall_attentionsr   blockpooling_flagpooled_hiddenlayer_indexlayerrepeat_index
do_poolingr  r  r   layer_outputs                           r@   rY   zTFFunnelEncoder.cally  s     33II))	 J 
 0D],$0d"+DKK"8 	JK%f-a09J9JAPQRL';K!OLHHZ%78M262J2J2`2`,3// '0&6 J"U$)$*<*<[*I$J JL".!"3!\+:J!\P\J! -040@0@fmSe.444e#(sE+;O`ks$L *!_F!+/+C+C+Z+Z[k+l(()7,qr:J)J+,=	,I)#JJ	J< aV->$Oaaa 6IZguvvrA   c                    | j                   ry d| _         | j                  D ]B  }|D ];  }t        j                  |j                        5  |j                  d        d d d        = D y # 1 sw Y   JxY w)NT)rL   rG  rH   rI   r-   rN   )r=   rQ   rY  r]  s       r@   rN   zTFFunnelEncoder.build  sk    ::
[[ 	&E &]]5::. &KK%& &&	&& &s   A''A0NNFFTFrZ   r4  ra   s   @r@   rA  rA  m  s(    	
 "7wr&rA   rA  c                (   |dk(  r| S |r| ddddf   }| ddddf   } t        j                  | |d      }|rM|r"t        j                  |ddgd|dz
  gddgg      }|ddd|dz
  f   }t        j                  |gd      }|S |ddd|f   }|S )z{
    Upsample tensor `x` to match `target_len` by repeating the tokens `stride` time on the sequence length dimension.
    r$   N)repeatsr   r   r   )rH   repeatrx   r   )r   r   
target_lenrj   rk   clsr   s          r@   upsamplerh    s     {2A2haeHYYq&q1FVVFaVa!_q!f$EFF+Z!^++,C=q1 M ;J;'MrA   c                  :     e Zd Z fdZ	 	 	 	 	 	 ddZddZ xZS )TFFunnelDecoderc           	     @   t        |   di | |j                  | _        |j                  | _        dt	        |j
                        dz
  z  | _        t        |      | _        t        |j                        D cg c]  }t        |dd|        c}| _        y c c}w )Nrd   r$   r   z	layers_._r9  r/   )r0   r1   rj   rk   r   rF  r   rc   rD  r   num_decoder_layersr6  r5   )r=   r2   r>   rI  r?   s       r@   r1   zTFFunnelDecoder.__init__  s    "6""//"//C 2 23a78#=f#E OTU[UnUnOop!}VQy_Epps   :Bc	           	        t        || j                  t        |      d   | j                  | j                        }	|	|z   }
|r|
fnd }|rdnd }| j
                  j                  |
|||      }| j                  D ](  } ||
|
|
|||      }|d   }
|r||dd  z   }|s#||
fz   }* |st        d |
||fD              S t        |
||      S )	Nr$   )r   rf  rj   rk   r/   rK  r<  r   c              3  &   K   | ]	  }||  y wrZ   r/   rM  s     r@   r   z'TFFunnelDecoder.call.<locals>.<genexpr>  rN  rO  rP  )
rh  r   r   rj   rk   rD  r   r5   r   r
   )r=   final_hiddenfirst_block_hiddenrz   r{   r  rU  rV  rT   upsampled_hiddenr1  rW  rX  r   r]  r`  s                   r@   rY   zTFFunnelDecoder.call  s    $;;!"45a8****
 "$66)=VI40d33II))	 J 
 [[ 		BE (8L]hpL "!_F !/,qr2B!B#$5	$A!		B aV->$Oaaa 6IZguvvrA   c                    | j                   ry d| _         t        | dd       K| j                  D ];  }t        j                  |j
                        5  |j                  d        d d d        = y y # 1 sw Y   IxY w)NTr5   )rL   rM   r5   rH   rI   r-   rN   )r=   rQ   r]  s      r@   rN   zTFFunnelDecoder.build  sp    ::
44(4 &]]5::. &KK%& && 5& &s   A..A7	rb  rZ   r4  ra   s   @r@   rj  rj    s)    q "+wZ&rA   rj  c                  b     e Zd ZdZeZ fdZd Zd Zd Z	e
	 	 	 	 	 	 	 	 dd       Zd	dZ xZS )
TFFunnelBaseLayerzBase model without decoderc                    t        |   di | || _        |j                  | _        |j                  | _        |j
                  | _        t        |d      | _        t        |d      | _
        y )N
embeddingsr9  encoderr/   )r0   r1   r2   r  rU  use_return_dictrV  r'   rv  rA  rw  r<   s      r@   r1   zTFFunnelBaseLayer.__init__  s`    "6"!'!9!9$*$?$?!!11,V,G&vI>rA   c                    | j                   S rZ   rv  r=   s    r@   get_input_embeddingsz&TFFunnelBaseLayer.get_input_embeddings!      rA   c                `    || j                   _        t        |      d   | j                   _        y Nr   rv  rD   r   rK   r=   r   s     r@   set_input_embeddingsz&TFFunnelBaseLayer.set_input_embeddings$  $    !&%/%6q%9"rA   c                    t         rZ   r   r=   heads_to_prunes     r@   _prune_headszTFFunnelBaseLayer._prune_heads(      !!rA   c	           	     2   ||t        d      |t        |      }	n|t        |      d d }	nt        d      |t        j                  |	d      }|t        j                  |	d      }|| j	                  ||      }| j                  |||||||      }
|
S )NDYou cannot specify both input_ids and inputs_embeds at the same timer   5You have to specify either input_ids or inputs_embedsr$   r   rr   rz   r{   r  rU  rV  rT   )
ValueErrorr   rH   r   rv  rw  )r=   rV   rz   r{   rW   r  rU  rV  rT   rQ   encoder_outputss              r@   rY   zTFFunnelBaseLayer.call+  s      ]%>cdd"$Y/K&$]3CR8KTUU!WW[!4N!WW[!4N  OOIOIM,,))/!5# ' 
 rA   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   exY w# 1 sw Y   y xY w)NTrv  rw  )rL   rM   rH   rI   rv  r-   rN   rw  rP   s     r@   rN   zTFFunnelBaseLayer.buildU  s    ::
4t,8t334 ,%%d+,4D)5t||001 )""4() ) 6, ,) )r?  NNNNNNNFrZ   r\   r]   r^   r_   r%   config_classr1   r|  r  r  r   rY   rN   r`   ra   s   @r@   rt  rt    sS    $L	?:"  !' 'R	)rA   rt  c                  b     e Zd ZdZeZ fdZd Zd Zd Z	e
	 	 	 	 	 	 	 	 dd       Zd	dZ xZS )
TFFunnelMainLayerzBase model with decoderc                &   t        |   di | || _        |j                  | _        |j                  | _        |j
                  | _        |j                  | _        t        |d      | _	        t        |d      | _        t        |d      | _        y )Nrv  r9  rw  decoderr/   )r0   r1   r2   rF  r  rU  rx  rV  r'   rv  rA  rw  rj  r  r<   s      r@   r1   zTFFunnelMainLayer.__init__g  s|    "6"!--!'!9!9$*$?$?!!11,V,G&vI>&vI>rA   c                    | j                   S rZ   rz  r{  s    r@   r|  z&TFFunnelMainLayer.get_input_embeddingst  r}  rA   c                `    || j                   _        t        |      d   | j                   _        y r  r  r  s     r@   r  z&TFFunnelMainLayer.set_input_embeddingsw  r  rA   c                    t         rZ   r  r  s     r@   r  zTFFunnelMainLayer._prune_heads{  r  rA   c	           
        ||t        d      |t        |      }	n|t        |      d d }	nt        d      |t        j                  |	d      }|t        j                  |	d      }|| j	                  ||      }| j                  ||||d||      }
| j                  |
d   |
d   | j                  d      ||||||	      }|s6d}|d   f}|r|dz  }||
d   ||   z   fz   }|r|dz  }||
d
   ||   z   fz   }|S t        |d   |r|
j                  |j                  z   nd |r|
j                  |j                  z         S d       S )Nr  r   r  r$   r   rr   Tr  )ro  rp  rz   r{   r  rU  rV  rT   rd   rP  )r  r   rH   r   rv  rw  r  rF  r
   rR  rS  )r=   rV   rz   r{   rW   r  rU  rV  rT   rQ   r  decoder_outputsidxoutputss                 r@   rY   zTFFunnelMainLayer.call~  s     ]%>cdd"$Y/K&$]3CR8KTUU!WW[!4N!WW[!4N  OOIOIM,,))/!%# ' 
 ,,(+.q1$2B2B12EF))/!5# ' 	
 C&q)+G#q!_Q%7/#:N%N$PP q!_Q%7/#:N%N$PPN -a0# +88?;X;XXTe22_5O5OO
 	

 lp
 	
rA   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   xY w# 1 sw Y   qxY w# 1 sw Y   y xY w)NTrv  rw  r  )	rL   rM   rH   rI   rv  r-   rN   rw  r  rP   s     r@   rN   zTFFunnelMainLayer.build  s   ::
4t,8t334 ,%%d+,4D)5t||001 )""4()4D)5t||001 )""4() ) 6, ,) )) )s$   D%%D1?D=%D.1D:=Er  rZ   r  ra   s   @r@   r  r  a  sU    !L?:"  !C
 C
J)rA   r  c                  0     e Zd ZdZ fdZd ZddZ xZS ) TFFunnelDiscriminatorPredictionszEPrediction module for the discriminator, made up of two dense layers.c                @   t        |   di | t        |j                        }t        j
                  j                  |j                  |d      | _        t        |j                        | _        t        j
                  j                  d|d      | _        || _        y )Ndenser   r$   dense_predictionr/   )r0   r1   r   rE   r   r5   r   rO   r  r	   r+  r,  r  r2   r.  s       r@   r1   z)TFFunnelDiscriminatorPredictions.__init__  s~    "6"%f&>&>?\\'';]d'e
#4V5F5F#G  % 2 21[m 2 nrA   c                    | j                  |      }| j                  |      }t        j                  | j	                  |            }|S rZ   )r  r,  rH   r   r  )r=   discriminator_hidden_statesrR  logitss       r@   rY   z%TFFunnelDiscriminatorPredictions.call  s?    

#>?00?D11-@ArA   c                "   | j                   ry d| _         t        | dd       dt        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   |xY w# 1 sw Y   y xY w)NTr  r  )
rL   rM   rH   rI   r  r-   rN   r2   rO   r  rP   s     r@   rN   z&TFFunnelDiscriminatorPredictions.build  s    ::
4$'3tzz/ D

  $dkk.A.A!BCD4+T2>t4499: O%%++T49L9L,MNO O ?D DO O   3C9<3D9DDrZ   )r\   r]   r^   r_   r1   rY   rN   r`   ra   s   @r@   r  r    s    O	OrA   r  c                  H     e Zd Z fdZ fdZd Zd Zd Zd ZddZ	 xZ
S )	TFFunnelMaskedLMHeadc                b    t        |   di | || _        |j                  | _        || _        y )Nr/   )r0   r1   r2   r3   input_embeddings)r=   r2   r  r>   r?   s       r@   r1   zTFFunnelMaskedLMHead.__init__  s0    "6"!-- 0rA   c                    | j                  | j                  j                  fddd      | _        t        |   |       y )NrT  Tbiasr   )rJ   r2   rK   r  r0   rN   )r=   rQ   r?   s     r@   rN   zTFFunnelMaskedLMHead.build  s7    OO4;;+A+A*CQXdhouOv	k"rA   c                    | j                   S rZ   )r  r{  s    r@   get_output_embeddingsz*TFFunnelMaskedLMHead.get_output_embeddings  s    $$$rA   c                `    || j                   _        t        |      d   | j                   _        y r  )r  rD   r   rK   r  s     r@   set_output_embeddingsz*TFFunnelMaskedLMHead.set_output_embeddings  s(    ',$+5e+<Q+?(rA   c                    d| j                   iS )Nr  )r  r{  s    r@   get_biaszTFFunnelMaskedLMHead.get_bias  s    		""rA   c                X    |d   | _         t        |d         d   | j                  _        y )Nr  r   )r  r   r2   rK   r  s     r@   set_biaszTFFunnelMaskedLMHead.set_bias  s'    &M	!+E&M!:1!=rA   c                t   t        |      d   }t        j                  |d| j                  g      }t        j                  || j
                  j                  d      }t        j                  |d|| j                  j                  g      }t        j                  j                  || j                        }|S )N)r   r$   r   )r   rF   T)abtranspose_b)r   r  )r   rH   r   r3   matmulr  rD   r2   rK   r   bias_addr  )r=   rR  rT   
seq_lengths       r@   rY   zTFFunnelMaskedLMHead.call
  s    }5a8


-DDTDT?UV		MT5J5J5Q5Q_cd

-JPTP[P[PfPf?gh]KrA   r   )r\   r]   r^   r1   rN   r  r  r  r  rY   r`   ra   s   @r@   r  r    s'    1#
%@#>rA   r  c                  .     e Zd Z fdZddZddZ xZS )TFFunnelClassificationHeadc                h   t        |   di | t        |j                        }t        j
                  j                  |j                  |d      | _        t        j
                  j                  |j                        | _        t        j
                  j                  ||d      | _        || _        y )Nlinear_hiddenr   
linear_outr/   )r0   r1   r   rE   r   r5   r   rO   r  r9   r:   r;   r  r2   )r=   r2   n_labelsr>   rG   r?   s        r@   r1   z#TFFunnelClassificationHead.__init__  s    "6"%f&>&>?"\\//S^et/u||++F,A,AB,,,,X+\h,irA   c                    | j                  |      }t        j                  j                  |      }| j	                  ||      }| j                  |      S r0  )r  r   activationstanhr;   r  )r=   r1  rT   s      r@   rY   zTFFunnelClassificationHead.call  sI    ##F+""''/fx8v&&rA   c                "   | j                   ry d| _         t        | dd       dt        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   |xY w# 1 sw Y   y xY w)NTr  r  )
rL   rM   rH   rI   r  r-   rN   r2   rO   r  rP   s     r@   rN   z TFFunnelClassificationHead.build#  s    ::
4$/;t11667 L""(($dkk6I6I)JKL4t,8t334 I%%tT4;;3F3F&GHI I 9L LI Ir  r   rZ   r4  ra   s   @r@   r  r    s    '	IrA   r  c                  (    e Zd ZdZeZdZed        Zy)TFFunnelPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    funnelc                P    dt        j                  dt         j                        iS )NrV   )r$   r   rs   rH   ry   int32r{  s    r@   dummy_inputsz$TFFunnelPreTrainedModel.dummy_inputs8  s     RWWV288<==rA   N)	r\   r]   r^   r_   r%   r  base_model_prefixpropertyr  r/   rA   r@   r  r  /  s&    
  L > >rA   r  c                  <    e Zd ZU dZdZded<   dZded<   dZded<   y)TFFunnelForPreTrainingOutputa&  
    Output type of [`FunnelForPreTraining`].

    Args:
        logits (`tf.Tensor` of shape `(batch_size, sequence_length)`):
            Prediction scores of the head (scores for each token before SoftMax).
        hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
            `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the initial embedding outputs.
        attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
    Nz	tf.Tensorr  zTuple[tf.Tensor] | NonerR  rS  )r\   r]   r^   r_   r  r   rR  rS  r/   rA   r@   r  r  >  s)    & FI-1M*1*.J'.rA   r  aa
  

    The Funnel Transformer model was proposed in [Funnel-Transformer: Filtering out Sequential Redundancy for Efficient
    Language Processing](https://arxiv.org/abs/2006.03236) by Zihang Dai, Guokun Lai, Yiming Yang, Quoc V. Le.

    This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
    as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
    behavior.

    <Tip>

    TensorFlow models and layers in `transformers` accept two formats as input:

    - having all inputs as keyword arguments (like PyTorch models), or
    - having all inputs as a list, tuple or dict in the first positional argument.

    The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
    and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
    pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
    format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
    the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
    positional argument:

    - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
    - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
    `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
    - a dictionary with one or several input Tensors associated to the input names given in the docstring:
    `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`

    Note that when creating models and layers with
    [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
    about any of this, as you can just pass inputs like you would to any other Python function!

    </Tip>

    Parameters:
        config ([`XxxConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
a
  
    Args:
        input_ids (`Numpy array` or `tf.Tensor` of shape `({0})`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
            [`PreTrainedTokenizer.encode`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        token_type_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
            1]`:

            - 0 corresponds to a *sentence A* token,
            - 1 corresponds to a *sentence B* token.

            [What are token type IDs?](../glossary#token-type-ids)
        inputs_embeds (`tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
            config will be used instead.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
            used instead.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
            eager mode, in graph mode the value will always be set to True.
        training (`bool`, *optional*, defaults to `False`):
            Whether or not to use the model in training mode (some modules like dropout modules have different
            behaviors between training and evaluation).
z
    The base Funnel Transformer Model transformer outputting raw hidden-states without upsampling head (also called
    decoder) or any task-specific head on top.
    c                       e Zd Zd fdZ eej                  d             edee	      e
	 	 	 	 	 	 	 	 d		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d
d                     Zd ZddZ xZS )TFFunnelBaseModelc                P    t        |   |g|i | t        |d      | _        y Nr  r9  )r0   r1   rt  r  r=   r2   rS   r>   r?   s       r@   r1   zTFFunnelBaseModel.__init__  (    3&3F3'X>rA   batch_size, sequence_lengthfunnel-transformer/small-base
checkpointoutput_typer  c	           
     4    | j                  ||||||||      S N)rV   rz   r{   rW   r  rU  rV  rT   r  	r=   rV   rz   r{   rW   r  rU  rV  rT   s	            r@   rY   zTFFunnelBaseModel.call  2    $ {{))'/!5#  	
 		
rA   c                Z    t        |j                  |j                  |j                        S NrP  r
   rQ  rR  rS  r=   r   s     r@   serving_outputz TFFunnelBaseModel.serving_output  ,     !$66 ..((
 	
rA   c                    | j                   ry d| _         t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   y xY wNTr  rL   rM   rH   rI   r  r-   rN   rP   s     r@   rN   zTFFunnelBaseModel.build  i    ::
44(4t{{//0 (!!$'( ( 5( (   A11A:r2   r%   returnNoner  rV   TFModelInputType | Nonerz   np.ndarray | tf.Tensor | Noner{   r  rW   r  r  Optional[bool]rU  r  rV  r  rT   boolr  z*Union[Tuple[tf.Tensor], TFBaseModelOutput]rZ   )r\   r]   r^   r1   r!   FUNNEL_INPUTS_DOCSTRINGformatr   r
   _CONFIG_FOR_DOCr   rY   r  rN   r`   ra   s   @r@   r  r    s    ? ++B+I+IJg+hi2%$
  .28<8<7;,0/3&*
*
 6
 6	

 5
 *
 -
 $
 
 
4
  j
,
(rA   r  zlThe bare Funnel Transformer Model transformer outputting raw hidden-states without any specific head on top.c                       e Zd Zd fdZe eej                  d             ede	e
      	 	 	 	 	 	 	 	 d		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d
d                     Zd ZddZ xZS )TFFunnelModelc                P    t        |   |g|i | t        |d      | _        y r  )r0   r1   r  r  r  s       r@   r1   zTFFunnelModel.__init__  r  rA   r  funnel-transformer/smallr  c	           
     4    | j                  ||||||||      S r  r  r  s	            r@   rY   zTFFunnelModel.call  r  rA   c                Z    t        |j                  |j                  |j                        S r  r  r  s     r@   r  zTFFunnelModel.serving_output  r  rA   c                    | j                   ry d| _         t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   y xY wr  r  rP   s     r@   rN   zTFFunnelModel.build  r  r  r  r  r  rZ   )r\   r]   r^   r1   r   r!   r  r  r   r
   r  rY   r  rN   r`   ra   s   @r@   r  r    s    
? *+B+I+IJg+hi-%$ .28<8<7;,0/3&*
*
 6
 6	

 5
 *
 -
 $
 
 
4
 j 
,
(rA   r  z|
    Funnel model with a binary classification head on top as used during pretraining for identifying generated tokens.
    c                       e Zd Zd fdZe eej                  d             ee	e
      	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	d                     Zd Zd
dZ xZS )TFFunnelForPreTrainingc                n    t        |   |fi | t        |d      | _        t	        |d      | _        y )Nr  r9  discriminator_predictions)r0   r1   r  r  r  r  r<   s      r@   r1   zTFFunnelForPreTraining.__init__,  s3    *6*'X>)I&Wr)s&rA   r  )r  r  c	           
         | j                  ||||||||      }
|
d   }| j                  |      }|s	|f|
dd z   S t        ||
j                  |
j                        S )a  
        Returns:

        Examples:

        ```python
        >>> from transformers import AutoTokenizer, TFFunnelForPreTraining
        >>> import torch

        >>> tokenizer = AutoTokenizer.from_pretrained("funnel-transformer/small")
        >>> model = TFFunnelForPreTraining.from_pretrained("funnel-transformer/small")

        >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
        >>> logits = model(inputs).logits
        ```rV  rT   r   r$   Nr  rR  rS  )r  r  r  rR  rS  )r=   rV   rz   r{   rW   r  rU  rV  rT   r>   r  discriminator_sequence_outputr  s                r@   rY   zTFFunnelForPreTraining.call2  s    < '+kk # '2 	'
# )DA(F%//0MN9:12>>>+5CC2==
 	
rA   c                Z    t        |j                  |j                  |j                        S Nr  )r  r  rR  rS  r  s     r@   r  z%TFFunnelForPreTraining.serving_outputf  s)     ,==0D0DQWQbQb
 	
rA   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   exY w# 1 sw Y   y xY w)NTr  r  )rL   rM   rH   rI   r  r-   rN   r  rP   s     r@   rN   zTFFunnelForPreTraining.buildm  s    ::
44(4t{{//0 (!!$'(44d;Gt==BBC ;..44T:; ; H( (; ;r?  r  r  )rV   r  rz   r  r{   r  rW   r  r  r  rU  r  rV  r  rT   r  r  z5Union[Tuple[tf.Tensor], TFFunnelForPreTrainingOutput]rZ   )r\   r]   r^   r1   r   r!   r  r  r#   r  r  rY   r  rN   r`   ra   s   @r@   r  r  %  s    t *+B+I+IJg+hi+GVef .28<8<7;,0/3&*/
*/
 6/
 6	/

 5/
 */
 -/
 $/
 /
 
?/
 g j /
b
	;rA   r  z4Funnel Model with a `language modeling` head on top.c                       e Zd Zd
 fdZddZddZe eej                  d             e
dee      	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZdd	Z xZS )TFFunnelForMaskedLMc                    t        |   |g|i | t        |d      | _        t	        || j                  j
                  d      | _        y )Nr  r9  lm_head)r0   r1   r  r  r  rv  r  r  s       r@   r1   zTFFunnelForMaskedLM.__init__{  sC    3&3F3'X>+FDKK4J4JQZ[rA   c                    | j                   S rZ   )r  r{  s    r@   get_lm_headzTFFunnelForMaskedLM.get_lm_head  s    ||rA   c                    t        j                  dt               | j                  dz   | j                  j                  z   S )NzMThe method get_prefix_bias_name is deprecated. Please use `get_bias` instead./)warningswarnFutureWarningr-   r  r{  s    r@   get_prefix_bias_namez(TFFunnelForMaskedLM.get_prefix_bias_name  s/    egtuyy3!2!222rA   r  r  r  c
           
         | j                  ||||||||	      }
|
d   }| j                  ||	      }|dn| j                  ||      }|s|f|
dd z   }||f|z   S |S t        |||
j                  |
j
                        S )a  
        labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
            config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
            loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
        r  r   rr   Nr$   lossr  rR  rS  )r  r  hf_compute_lossr   rR  rS  )r=   rV   rz   r{   rW   r  rU  rV  labelsrT   r  sequence_outputprediction_scoresr  r   s                  r@   rY   zTFFunnelForMaskedLM.call  s    2 ++ #  	
 "!* LL8LL~t4+?+?HY+Z')GABK7F)-)9TGf$EvE$!//))	
 	
rA   c                Z    t        |j                  |j                  |j                        S r
  )r   r  rR  rS  r  s     r@   r  z"TFFunnelForMaskedLM.serving_output  s$      v}}FDXDXekevevwwrA   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   exY w# 1 sw Y   y xY w)NTr  r  )rL   rM   rH   rI   r  r-   rN   r  rP   s     r@   rN   zTFFunnelForMaskedLM.build  s    ::
44(4t{{//0 (!!$'(4D)5t||001 )""4() ) 6( () )r?  r  )r  r  )r  str	NNNNNNNNF)rV   r  rz   r  r{   r  rW   r  r  r  rU  r  rV  r  r  r  rT   r  r  z)Union[Tuple[tf.Tensor], TFMaskedLMOutput])r   r   r  r   rZ   )r\   r]   r^   r1   r  r  r   r!   r  r  r   r   r  rY   r  rN   r`   ra   s   @r@   r  r  y  s    \3 *+B+I+IJg+hi-$$ .28<8<7;,0/3&*04*
**
 6*
 6	*

 5*
 **
 -*
 $*
 .*
 *
 
3*
 j *
Xx
	)rA   r  z
    Funnel Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
    output) e.g. for GLUE tasks.
    c                       e Zd Zd fdZe eej                  d             ede	e
      	 	 	 	 	 	 	 	 	 d		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d
d                     ZddZddZ xZS )!TFFunnelForSequenceClassificationc                    t        |   |g|i | |j                  | _        t        |d      | _        t        ||j                  d      | _        y )Nr  r9  
classifier)r0   r1   
num_labelsrt  r  r  r&  r  s       r@   r1   z*TFFunnelForSequenceClassification.__init__  sL    3&3F3 ++'X>4VV=N=NUabrA   r  r  r  c
           
        | j                  ||||||||	      }
|
d   }|dddf   }| j                  ||	      }|dn| j                  ||      }|s|f|
dd z   }||f|z   S |S t        |||
j                  |
j
                        S )a  
        labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        r  r   Nrr   r$   r  )r  r&  r  r   rR  rS  )r=   rV   rz   r{   rW   r  rU  rV  r  rT   r  rQ  pooled_outputr  r  r   s                   r@   rY   z&TFFunnelForSequenceClassification.call  s    2 ++ #  	
 $AJ)!Q$/B~t4+?+?+OY,F)-)9TGf$EvE)!//))	
 	
rA   c                Z    t        |j                  |j                  |j                        S r
  )r   r  rR  rS  r  s     r@   r  z0TFFunnelForSequenceClassification.serving_output  s)     *==0D0DQWQbQb
 	
rA   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   exY w# 1 sw Y   y xY wNTr  r&  rL   rM   rH   rI   r  r-   rN   r&  rP   s     r@   rN   z'TFFunnelForSequenceClassification.build      ::
44(4t{{//0 (!!$'(4t,8t334 ,%%d+, , 9( (, ,r?  r  r"  )rV   r  rz   r  r{   r  rW   r  r  r  rU  r  rV  r  r  r  rT   r  r  z3Union[Tuple[tf.Tensor], TFSequenceClassifierOutput])r   r   r  r   rZ   )r\   r]   r^   r1   r   r!   r  r  r   r   r  rY   r  rN   r`   ra   s   @r@   r$  r$    s    c *+B+I+IJg+hi2.$ .28<8<7;,0/3&*04+
*+
 6+
 6	+

 5+
 *+
 -+
 $+
 .+
 +
 
=+
 j +
Z
	,rA   r$  z
    Funnel Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
    softmax) e.g. for RocStories/SWAG tasks.
    c                       e Zd Zd	 fdZed        Ze eej                  d             e
dee      	 	 	 	 	 	 	 	 	 d
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZddZ xZS )TFFunnelForMultipleChoicec                v    t        |   |g|i | t        |d      | _        t	        |dd      | _        y )Nr  r9  r$   r&  )r0   r1   rt  r  r  r&  r  s       r@   r1   z"TFFunnelForMultipleChoice.__init__*  s8    3&3F3'X>4VQ\RrA   c                P    dt        j                  dt         j                        iS )NrV   )r   r      rs   r  r{  s    r@   r  z&TFFunnelForMultipleChoice.dummy_inputs0  s    RWWYbhh?@@rA   z(batch_size, num_choices, sequence_lengthr  r  c
           
        |t        |      d   }
t        |      d   }nt        |      d   }
t        |      d   }|t        j                  |d|f      nd}|t        j                  |d|f      nd}|t        j                  |d|f      nd}|%t        j                  |d|t        |      d   f      nd}| j                  ||||||||	      }|d   }|dddf   }| j	                  ||	      }t        j                  |d|
f      }|dn| j                  ||      }|s|f|dd z   }||f|z   S |S t        |||j                  |j                  	      S )
a5  
        labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
            where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
        Nr$   rd   r   r   )rz   r{   rW   r  rU  rV  rT   r   rr   r  )	r   rH   r   r  r&  r  r   rR  rS  )r=   rV   rz   r{   rW   r  rU  rV  r  rT   num_choicesr  flat_input_idsflat_attention_maskflat_token_type_idsflat_inputs_embedsr  rQ  r)  r  reshaped_logitsr  r   s                          r@   rY   zTFFunnelForMultipleChoice.call4  s   0  $Y/2K#I.q1J$]3A6K#M215JDMDYIJ/?@_cN\Nhbjj"j9IJnrN\Nhbjj"j9IJnr ( JJ}r:z-7PQR7S&TU 	 ++..,/!5#  	
 $AJ)!Q$/B**Vb+->?~t4+?+?+X%''!"+5F)-)9TGf$EvE*"!//))	
 	
rA   c                Z    t        |j                  |j                  |j                        S r
  )r   r  rR  rS  r  s     r@   r  z(TFFunnelForMultipleChoice.serving_outputy  s)     +==0D0DQWQbQb
 	
rA   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   exY w# 1 sw Y   y xY wr,  r-  rP   s     r@   rN   zTFFunnelForMultipleChoice.build  r.  r?  r  r"  )rV   r  rz   r  r{   r  rW   r  r  r  rU  r  rV  r  r  r  rT   r  r  z4Union[Tuple[tf.Tensor], TFMultipleChoiceModelOutput])r   r   r  r   rZ   )r\   r]   r^   r1   r  r  r   r!   r  r  r   r   r  rY   r  rN   r`   ra   s   @r@   r0  r0  "  s    S A A *+B+I+IJt+uv2/$ .28<8<7;,0/3&*04<
*<
 6<
 6	<

 5<
 *<
 -<
 $<
 .<
 <
 
><
 w <
|
	,rA   r0  z
    Funnel Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
    Named-Entity-Recognition (NER) tasks.
    c                       e Zd Zd fdZe eej                  d             ede	e
      	 	 	 	 	 	 	 	 	 d		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d
d                     ZddZddZ xZS )TFFunnelForTokenClassificationc                d   t        |   |g|i | |j                  | _        t        |d      | _        t
        j                  j                  |j                        | _	        t
        j                  j                  |j                  t        |j                        d      | _        || _        y )Nr  r9  r&  r   )r0   r1   r'  r  r  r   r5   r9   r:   r;   r   r   rE   r&  r2   r  s       r@   r1   z'TFFunnelForTokenClassification.__init__  s    3&3F3 ++'X>||++F,A,AB,,,,/&BZBZ2[bn - 
 rA   r  r  r  c
           
     "   | j                  ||||||||	      }
|
d   }| j                  ||	      }| j                  |      }|dn| j                  ||      }|s|f|
dd z   }||f|z   S |S t	        |||
j
                  |
j                        S )z
        labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
        r  r   rr   Nr$   r  )r  r;   r&  r  r   rR  rS  )r=   rV   rz   r{   rW   r  rU  rV  r  rT   r  r  r  r  r   s                  r@   rY   z#TFFunnelForTokenClassification.call  s    . ++ #  	
 "!*,,,J1~t4+?+?+OY,F)-)9TGf$EvE&!//))	
 	
rA   c                Z    t        |j                  |j                  |j                        S r
  )r   r  rR  rS  r  s     r@   r  z-TFFunnelForTokenClassification.serving_output  s)     '==0D0DQWQbQb
 	
rA   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   |xY w# 1 sw Y   y xY wr,  )
rL   rM   rH   rI   r  r-   rN   r&  r2   r3   rP   s     r@   rN   z$TFFunnelForTokenClassification.build      ::
44(4t{{//0 (!!$'(4t,8t334 M%%tT4;;3J3J&KLM M 9( (M M   C"%3C."C+.C7r  r"  )rV   r  rz   r  r{   r  rW   r  r  r  rU  r  rV  r  r  r  rT   r  r  z0Union[Tuple[tf.Tensor], TFTokenClassifierOutput])r   r   r  r   rZ   )r\   r]   r^   r1   r   r!   r  r  r   r   r  rY   r  rN   r`   ra   s   @r@   r>  r>    s    	 *+B+I+IJg+hi-+$ .28<8<7;,0/3&*04*
**
 6*
 6	*

 5*
 **
 -*
 $*
 .*
 *
 
:*
 j *
X
	MrA   r>  z
    Funnel Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
    layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
    c                       e Zd Zd fdZe eej                  d             ede	e
      	 	 	 	 	 	 	 	 	 	 d		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d
d                     ZddZddZ xZS )TFFunnelForQuestionAnsweringc                   t        |   |g|i | |j                  | _        t        |d      | _        t
        j                  j                  |j                  t        |j                        d      | _
        || _        y )Nr  r9  
qa_outputsr   )r0   r1   r'  r  r  r   r5   r   r   rE   rH  r2   r  s       r@   r1   z%TFFunnelForQuestionAnswering.__init__  sr    3&3F3 ++'X>,,,,/&BZBZ2[bn - 
 rA   r  r  r  c           
        | j                  ||||||||
      }|d   }| j                  |      }t        j                  |dd      \  }}t        j                  |d      }t        j                  |d      }d}||	||	d}| j                  |||f      }|s||f|dd z   }||f|z   S |S t        ||||j                  |j                  	      S )
a  
        start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        r  r   rd   r   r   N)start_positionend_positionr$   )r  start_logits
end_logitsrR  rS  )	r  rH  rH   r  r   r  r   rR  rS  )r=   rV   rz   r{   rW   r  rU  rV  start_positionsend_positionsrT   r  r  r  rL  rM  r  r  r   s                      r@   rY   z!TFFunnelForQuestionAnswering.call  s   > ++ #  	
 "!*1#%88FAB#? jzz,R8ZZ
4
&=+D(7WF''z0JKD"J/'!"+=F)-)9TGf$EvE-%!!//))
 	
rA   c                p    t        |j                  |j                  |j                  |j                        S )N)rL  rM  rR  rS  )r   rL  rM  rR  rS  r  s     r@   r  z+TFFunnelForQuestionAnswering.serving_output8  s5     .,,(( ..((	
 	
rA   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   |xY w# 1 sw Y   y xY w)NTr  rH  )
rL   rM   rH   rI   r  r-   rN   rH  r2   r3   rP   s     r@   rN   z"TFFunnelForQuestionAnswering.buildB  rC  rD  r  )
NNNNNNNNNF)rV   r  rz   r  r{   r  rW   r  r  r  rU  r  rV  r  rN  r  rO  r  rT   r  r  z7Union[Tuple[tf.Tensor], TFQuestionAnsweringModelOutput])r   r   r  r   rZ   )r\   r]   r^   r1   r   r!   r  r  r   r   r  rY   r  rN   r`   ra   s   @r@   rF  rF    s     *+B+I+IJg+hi-2$ .28<8<7;,0/3&*9=7;8
*8
 68
 6	8

 58
 *8
 -8
 $8
 78
 58
 8
 
A8
 j 8
t
	MrA   rF  )TF)Qr_   
__future__r   r  dataclassesr   typingr   r   r   numpynp
tensorflowrH   activations_tfr	   modeling_tf_outputsr
   r   r   r   r   r   modeling_tf_utilsr   r   r   r   r   r   r   r   r   r   r   tf_utilsr   r   r   utilsr   r   r    r!   r"   r#   configuration_funnelr%   
get_loggerr\   loggerr  r  r5   Layerr'   rc   r   r   r&  r6  rA  rh  rj  rt  r  r  r  r  r  r  FUNNEL_START_DOCSTRINGr  r  r  r  r  r$  r0  r>  rF  r/   rA   r@   <module>rb     sp    "  ! ) )   /     S R  / 
		H	%  
- ++ - `s  s l tGELL$6$6 tGn Iell00  IF%ELL&& %2L&ell(( L&^(=&ell(( =&@ M)** M) M)` n)** n) n)bOu||'9'9 O:!5<<-- !HI!3!3 I6>/ > /; / /2+ Z* Z  1(/ 1(1(h r1(+ 1(	1(h  	K;4 K;K;\ PRhiO)13O O) jO)d  L,(?A] L,L,^  `, 79M `,`,F  OM%<>W OMOMd  _M#:<S _M_MrA   