o
    ZhX:                    @  s  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,0e1Z2dZ3dZ4G dd de j5j6Z7G dd dZ8dd Z9G dd de j5j6Z:G dd de j5j6Z;G dd de j5j6Z<G dd de j5j6Z=dMd d!Z>G d"d# d#e j5j6Z?e!G d$d% d%e j5j6Z@e!G d&d' d'e j5j6ZAG d(d) d)e j5j6ZBG d*d+ d+e j5j6ZCG d,d- d-e j5j6ZDG d.d/ d/eZEeG d0d1 d1e(ZFd2ZGd3ZHe*d4eGG d5d6 d6eEZIe*d7eGG d8d9 d9eEZJe*d:eGG d;d< d<eEZKe*d=eGG d>d? d?eEeZLe*d@eGG dAdB dBeEeZMe*dCeGG dDdE dEeEeZNe*dFeGG dGdH dHeEeZOe*dIeGG dJdK dKeEeZPg dLZQdS )Nz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                      s4   e Zd ZdZ fddZd
ddZddd	Z  ZS )TFFunnelEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                   s`   t  jdi | || _|j| _|jd u rdn|j| _tjj|jdd| _	tjj
|jd| _d S )N      ?
layer_normepsilonname)Zrate )super__init__confighidden_sizeinitializer_stdr   layersLayerNormalizationlayer_norm_eps	LayerNormDropouthidden_dropoutdropoutselfr.   kwargs	__class__r+   \/var/www/auris/lib/python3.10/site-packages/transformers/models/funnel/modeling_tf_funnel.pyr-   G   s   zTFFunnelEmbeddings.__init__Nc                 C  s   t d | jd| jj| jgt| jdd| _W d    n1 s"w   Y  | j	r,d S d| _	t
| dd d ur\t | jj | jd d | jjg W d    d S 1 sUw   Y  d S d S )NZword_embeddingsweight)initializer_range)r*   shapeinitializerTr4   )tf
name_scope
add_weightr.   
vocab_sizer/   r   r0   r>   builtgetattrr4   r*   buildd_modelr9   input_shaper+   r+   r=   rH   Q   s   

"zTFFunnelEmbeddings.buildFc                 C  sj   |du r
|du r
J |dur|durJ |dur&t || jj t| j|}| j|d}| j||d}|S )z
        Applies embedding based on inputs tensor.

        Returns:
            final_embeddings (`tf.Tensor`): output embedding tensor.
        N)inputs)rL   training)r   r.   rE   rB   gatherr>   r4   r7   )r9   	input_idsinputs_embedsrM   Zfinal_embeddingsr+   r+   r=   call`   s   zTFFunnelEmbeddings.callNNNF)__name__
__module____qualname____doc__r-   rH   rQ   __classcell__r+   r+   r;   r=   r%   D   s
    

r%   c                   @  sv   e Zd ZU dZdZded< dd Zdd	d
Zdd ZdddZ	dd Z
dddZdd Zd ddZdd Zdd ZdS )!TFFunnelAttentionStructurez@
    Contains helpers for `TFFunnelRelMultiheadAttention `.
       intcls_token_type_idc                 C  sb   |j | _ |j| _|j| _|j| _|j| _|j| _|j| _tj	|j
| _tj	|j
| _d | _d S rR   )rI   attention_type
num_blocksseparate_clstruncate_seqpool_q_onlypooling_typer   r1   r5   r6   sin_dropoutcos_dropoutpooling_mult)r9   r.   r+   r+   r=   r-   {   s   
z#TFFunnelAttentionStructure.__init__NFc           	      C  s   d| _ t|d  | _}| j||d}|dur| |nd}| jr9ttj|d |d g|j	dddgddggnd}||||fS )zCReturns the attention inputs associated to the inputs of the model.r#   rM   Ndtyper   )
re   r   seq_lenget_position_embedstoken_type_ids_to_matr_   rB   padonesrh   )	r9   rP   attention_masktoken_type_idsrM   ri   position_embedstoken_type_matcls_maskr+   r+   r=   init_attention_inputs   s   2z0TFFunnelAttentionStructure.init_attention_inputsc                 C  s`   t t |dt |d}t |t j| jg|jd}t t |dt |d}t ||S )z-Convert `token_type_ids` to `token_type_mat`.rg   )rB   equalZexpand_dimsconstantr\   rh   
logical_or)r9   ro   rq   Zcls_idsZcls_matr+   r+   r=   rk      s   z0TFFunnelAttentionStructure.token_type_ids_to_matc                 C  sh  | j dkrktd|d}td| jd d}dd|| jd    }td||}t|}| j||d}t|}	| j|	|d}
tj	||gd	d
}tj	|	|gd	d
}tj	|
|
gd	d
}tj	| |	gd	d
}||||fS td| jd d}dd|| jd    }t| d |d d}|t
d }td||}| jt||d}| jt||d}	tj	||	gd	d
}td|}|}g }td| jD ]j}tjdgdd}|dkr| ||}d|d  }| j|||dd}tj||jd}|| }tj||dd
}|}d| }| ||}tj||jd}|| }tj|t|d  tj||dd
}|||g q|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&   rZ   r#   i'  zi,d->idrf   rt   axisg      )value)shiftrg   )r]   rB   rangerI   einsumsinrc   cosrd   concatrw   r^   fillstride_pool_posrelative_poscastrh   rN   	debuggingZassert_lessr@   append)r9   ri   rM   Zpos_seqZfreq_seqZinv_freqZsinusoidZ	sin_embedZsin_embed_dZ	cos_embedZcos_embed_dphipsipiomegaZ
rel_pos_idZzero_offsetZ	pos_embedpos
pooled_posZposition_embeds_listblock_indexZposition_embeds_poolingstrideZrel_posZposition_embeds_no_poolingr+   r+   r=   rj      sV   


z.TFFunnelAttentionStructure.get_position_embedsc                 C  sh   | j r-tjd|  d g|jd}| jr|dd n|dd }t||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`).
        rZ   r#   rg   rt   Nr   )r_   rB   rw   rh   r`   r   )r9   Zpos_idr   Zcls_posZpooled_pos_idr+   r+   r=   r      s
   z*TFFunnelAttentionStructure.stride_pool_posr#   c           	      C  s\   |du r|}|d |d  }|t |d  }|||  }|d |d  }t||d | S )zV
        Build the relative positional vector between `pos` and `pooled_pos`.
        Nr   rt   r#   )r   rB   r~   )	r9   r   r   r   r}   Z	ref_pointZ
num_removeZmax_distZmin_distr+   r+   r=   r     s   z'TFFunnelAttentionStructure.relative_posc                   s   |du rdS t  ttfr D ]}||}q|S t |ttfr/t| fdd|D S  tt|;  jrCjrCt	dddnt	ddd}t	dg  |g }jrmt	dg  t	ddg }t
|| |g }|| S )zT
        Perform pooling by stride slicing the tensor along the given axis.
        Nc                 3  s    | ]	} | V  qd S rR   )stride_pool.0xr{   r9   r+   r=   	<genexpr>       z9TFFunnelAttentionStructure.stride_pool.<locals>.<genexpr>rt   rZ   r#   )
isinstancelisttupler   typelenr   r_   r`   slicerB   r   )r9   tensorr{   axZ
axis_sliceZ	enc_sliceZ	cls_slicer+   r   r=   r     s   $z&TFFunnelAttentionStructure.stride_poolmeanc                   s.  du rdS t ttfrt fddD S jr@jr-ddddf n}tjddddf |gddtt	}|dkrUdddddf  dkretj
jd	d
dn& dkrutj
jd	d
dn dkrtj
j d	d
d ntd|dkrtdS S )z3Apply 1D pooling to a tensor of size [B x T (x H)].Nc                 3  s     | ]}j  d V  qdS ))moder   N)pool_tensorr   r   r9   r   r   r+   r=   r   3  s    z9TFFunnelAttentionStructure.pool_tensor.<locals>.<genexpr>rt   r#   rz   rZ   r   ZNWCZSAME)stridesZdata_formatpaddingmaxminz0The supported modes are 'mean', 'max' and 'min'.)r   r   r   r   r_   r`   rB   r   r   r   nnZ
avg_pool1dZ
max_pool1dNotImplementedErrorsqueeze)r9   r   r   r   suffixndimr+   r   r=   r   ,  s$    "z&TFFunnelAttentionStructure.pool_tensorc                 C  s   |\}}}}| j r3| jdkr| |dd d|dd  }| |d}| |d}| j|| jd}n1|  jd9  _| jdkrE| |d}| |ddg}| |ddg}| j|dd}| j|| jd}||||f}||fS )zTPool `output` and the proper parts of `attention_inputs` before the attention layer.ry   NrZ   r   r#   r   r   )ra   r]   r   r   rb   re   )r9   outputattention_inputsrp   rq   rn   rr   r+   r+   r=   pre_attention_poolingH  s    
 
z0TFFunnelAttentionStructure.pre_attention_poolingc                 C  s   |\}}}}| j r8|  jd9  _| jdkr%|dd | |dd d }| |d}| |d}| j|dd}||||f}|S )zFPool the proper parts of `attention_inputs` after the attention layer.rZ   ry   Nr   r#   r   r   )ra   re   r]   r   r   )r9   r   rp   rq   rn   rr   r+   r+   r=   post_attention_pooling\  s   
 z1TFFunnelAttentionStructure.post_attention_poolingrS   F)Nr#   )r   rZ   )rT   rU   rV   rW   r\   __annotations__r-   rs   rk   rj   r   r   r   r   r   r   r+   r+   r+   r=   rY   t   s   
 

S

rY   c                 C  sp   t | \}}}}t| ||||g} | d d d d |d d d f } t| ||||| g} | dd |f } | S )N.)r   rB   reshape)positional_attncontext_lenr}   
batch_sizen_headri   Zmax_rel_lenr+   r+   r=   _relative_shift_gatherj  s    r   c                      sD   e Zd Z fddZdddZdddZddd	ZdddZ  ZS )TFFunnelRelMultiheadAttentionc                   s   t  jdi | |j| _|j | _}|j | _}|j | _}|j| _|| _tj	
|j| _tj	
|j| _t|j}tj	j|| d|dd| _tj	j|| |dd| _tj	j|| |dd| _tj	j||dd| _tj	j|jdd	| _d
|d  | _d S )NFq_head)Zuse_biaskernel_initializerr*   k_headr   r*   v_head	post_projr'   r(   r&   g      ?r+   )r,   r-   r]   r   d_headrI   r?   r   r   r1   r5   r6   attention_dropoutr   Denser   r   r   r   r2   r3   r'   scale)r9   r.   r   r:   r   r   rI   rA   r;   r+   r=   r-   {  s$   
z&TFFunnelRelMultiheadAttention.__init__Nc                 C  sN  | j | j| j}}}t| j}| j||f|ddd| _| j||f|ddd| _| j|||f|ddd| _| j||f|ddd| _	| jd||f|ddd| _
| jrSd S d| _t| d	d d ur~t| jj | jd d |g W d    n1 syw   Y  t| d
d d urt| jj | jd d |g W d    n1 sw   Y  t| dd d urt| jj | jd d |g W d    n1 sw   Y  t| dd d urt| jj | jd d || g W d    n1 sw   Y  t| dd d ur%t| jj | jd d |g W d    d S 1 sw   Y  d S d S )NTr_w_biasr@   rA   Z	trainabler*   r_r_biasr_kernelr_s_biasrZ   	seg_embedr   r   r   r   r'   )r   r   rI   r   r?   rD   r   r   r   r   r   rF   rG   rB   rC   r   r*   rH   r   r   r   r'   )r9   rK   r   r   rI   rA   r+   r+   r=   rH     sR   
$z#TFFunnelRelMultiheadAttention.buildc                 C  s  | j dkr@|\}}}}| j| j }	| j}
td||	 |
}||dddf  }||dddf  }td||td|| }n:t|d |krRd}|| j d }n	d}|| j d }| j| j }| j}
td||
}td	|| |}t|||}|dur||9 }|S )
z5Relative attention score for the positional encodingsry   zbinh,dnh->bindNzbind,jd->bnijr#   rZ   r   ztd,dnh->tnhzbinh,tnh->bnit)	r]   r   r   r   rB   r   r   r   r   )r9   rp   r   r   rr   r   r   r   r   uZw_rZq_r_attentionZq_r_attention_1Zq_r_attention_2r   r}   rvZr_headr+   r+   r=   relative_positional_attention  s.   
z;TFFunnelRelMultiheadAttention.relative_positional_attentionc                 C  s   |du rdS t |\}}}| j| j }td|| | j}t|dddf dt |d ddg}tj|ddd\}	}
t|t|
ddd|gt|	ddd|g}|durZ||9 }|S )z/Relative attention score for the token_type_idsNr   zbind,snd->bnisr#   rZ   rt   rz   )	r   r   r   rB   r   r   Ztilesplitwhere)r9   rq   r   rr   r   ri   r   r   Ztoken_type_biasZdiff_token_typeZsame_token_typetoken_type_attnr+   r+   r=   relative_token_type_attention  s   (z;TFFunnelRelMultiheadAttention.relative_token_type_attentionFc              	   C  s|  |\}}}	}
t |\}}}t |d }| j| j}}t| |||||g}t| |||||g}t| |||||g}|| j }| j	| j }t
d|| |}| ||||
}| |||
}|| | }|	d urtj|	|jd}	|td|	d d d d f    }t|dd}| j||d}t
d||}| t||||| g}| j||d}| || }|r||fS |fS )Nr#   zbind,bjnd->bnijrg   rt   rz   rf   zbnij,bjnd->bind)r   r   r   rB   r   r   r   r   r   r   r   r   r   r   rh   INFr   r   r   r6   r'   )r9   querykeyr|   r   output_attentionsrM   rp   rq   rn   rr   r   ri   _r   r   r   r   r   r   r   Zcontent_scorer   r   Z
attn_scoreZ	attn_probZattn_vecZattn_outr   r+   r+   r=   rQ     s.   
z"TFFunnelRelMultiheadAttention.callrR   FF)	rT   rU   rV   r-   rH   r   r   rQ   rX   r+   r+   r;   r=   r   z  s    

'
.r   c                      0   e Zd Z fddZd	ddZd
ddZ  ZS )TFFunnelPositionwiseFFNc                   s   t  jdi | t|j}tjj|j|dd| _t	|j
| _tj|j| _tjj|j|dd| _tj|j| _tjj|jdd| _|| _d S )Nlinear_1r   linear_2r'   r(   r+   )r,   r-   r   r?   r   r1   r   d_innerr   r   
hidden_actactivation_functionr5   activation_dropoutrI   r   r6   r7   r2   r3   r'   r.   r9   r.   r:   rA   r;   r+   r=   r-   2  s   

z TFFunnelPositionwiseFFN.__init__Fc                 C  sH   |  |}| |}| j||d}| |}| j||d}| || S Nrf   )r   r   r   r   r7   r'   )r9   hiddenrM   hr+   r+   r=   rQ   =  s   


zTFFunnelPositionwiseFFN.callNc                 C  s  | j rd S d| _ t| dd d ur2t| jj | jd d | jjg W d    n1 s-w   Y  t| dd d ur\t| j	j | j	d d | jj
g W d    n1 sWw   Y  t| dd d urt| jj | jd d | jjg W d    d S 1 sw   Y  d S d S )NTr   r   r'   )rF   rG   rB   rC   r   r*   rH   r.   rI   r   r   r'   rJ   r+   r+   r=   rH   E  s    "zTFFunnelPositionwiseFFN.buildr   rR   rT   rU   rV   r-   rQ   rH   rX   r+   r+   r;   r=   r   1  s    
r   c                      r   )TFFunnelLayerc                   s4   t  jdi | t||dd| _t|dd| _d S )N	attentionr*   ffnr+   )r,   r-   r   r   r   r   )r9   r.   r   r:   r;   r+   r=   r-   U  s   zTFFunnelLayer.__init__Fc           	      C  s>   | j ||||||d}| j|d |d}|r||d fS |fS )Nr   rM   r   rf   r#   )r   r   )	r9   r   r   r|   r   r   rM   Zattnr   r+   r+   r=   rQ   Z  s
   zTFFunnelLayer.callNc                 C     | j rd S d| _ t| dd d ur-t| jj | jd  W d    n1 s(w   Y  t| dd d urUt| jj | jd  W d    d S 1 sNw   Y  d S d S )NTr   r   )rF   rG   rB   rC   r   r*   rH   r   rJ   r+   r+   r=   rH   a     "zTFFunnelLayer.buildr   rR   r   r+   r+   r;   r=   r   T  s    
r   c                      <   e Zd Z fddZ						d
ddZddd	Z  ZS )TFFunnelEncoderc                   sR   t  jdi |  j| _ j| _ j| _t | _ fddt jD | _	d S )Nc                   s(   g | ]\ } fd dt |D qS )c              	     s&   g | ]}t  d   d| dqS )z	blocks_._z_._r   r   r   i)r   r.   r+   r=   
<listcomp>u  s   & z7TFFunnelEncoder.__init__.<locals>.<listcomp>.<listcomp>)r~   )r   
block_sizer.   )r   r=   r   t  s    z,TFFunnelEncoder.__init__.<locals>.<listcomp>r+   )
r,   r-   r_   ra   block_repeatsrY   attention_structure	enumerateblock_sizesblocksr8   r;   r   r=   r-   n  s   

zTFFunnelEncoder.__init__NFTc                 C  sj  | j j||||d}|}	|r|fnd }
|rdnd }t| jD ]\}}t|	d | jr,dndk}|o4|dk}tt|	}|rG| j |	|\}}t|D ]S\}}t	| j
| D ]G}|dkoa|dkoa|}|rp|}| jrk|	n| }}n|	 } }}|||||||d}|d }	|r| j |}|r||dd   }|r|
|	f }
qVqKq|stdd |	|
|fD S t|	|
|d	S )
Nrn   ro   rM   r+   r#   rZ   r   r   c                 s      | ]	}|d ur|V  qd S rR   r+   r   r   r+   r+   r=   r     r   z'TFFunnelEncoder.call.<locals>.<genexpr>last_hidden_statehidden_states
attentions)r   rs   r   r   r   r_   rB   zerosr   r~   r   ra   r   r   r	   )r9   rP   rn   ro   r   output_hidden_statesreturn_dictrM   r   r   all_hidden_statesall_attentionsr   blockZpooling_flagZpooled_hiddenZlayer_indexlayerZrepeat_indexZ
do_poolingr   r   r|   layer_outputr+   r+   r=   rQ   y  sP   
zTFFunnelEncoder.callc              
   C  s`   | j rd S d| _ | jD ]"}|D ]}t|j |d  W d    n1 s'w   Y  qqd S )NT)rF   r   rB   rC   r*   rH   )r9   rK   r  r  r+   r+   r=   rH     s   
zTFFunnelEncoder.buildNNFFTFrR   r   r+   r+   r;   r=   r   m  s    
9r   TFc                 C  s   |dkr| S |r| ddddf }| ddddf } t j| |dd}|rP|r9t |ddgd|d gddgg}|ddd|d f }t j||gd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)Zrepeatsr{   r   rz   )rB   repeatrl   r   )r   r   
target_lenr_   r`   clsr   r+   r+   r=   upsample  s   "r  c                      r   )TFFunnelDecoderc                   s^   t  jdi |  j| _ j| _dt jd  | _t | _ fddt	 j
D | _d S )NrZ   r#   c                   s    g | ]}t  d d| dqS )r   z	layers_._r   r   r   r   r+   r=   r     s     z,TFFunnelDecoder.__init__.<locals>.<listcomp>r+   )r,   r-   r_   r`   r   r   r   rY   r   r~   Znum_decoder_layersr1   r8   r;   r   r=   r-     s   
zTFFunnelDecoder.__init__NFTc	              	   C  s   t || jt|d | j| jd}	|	| }
|r|
fnd }|rdnd }| jj|
|||d}| jD ]!}||
|
|
|||d}|d }
|rH||dd   }|rO||
f }q.|s^tdd |
||fD S t	|
||d	S )
Nr#   )r   r  r_   r`   r+   r   r   r   c                 s  r   rR   r+   r   r+   r+   r=   r     r   z'TFFunnelDecoder.call.<locals>.<genexpr>r   )
r  r   r   r_   r`   r   rs   r1   r   r	   )r9   final_hiddenfirst_block_hiddenrn   ro   r   r  r  rM   Zupsampled_hiddenr   r  r  r   r  r  r+   r+   r=   rQ     s:   


zTFFunnelDecoder.callc              	   C  sj   | j rd S d| _ t| dd d ur1| jD ]}t|j |d  W d    n1 s+w   Y  qd S d S )NTr1   )rF   rG   r1   rB   rC   r*   rH   )r9   rK   r  r+   r+   r=   rH     s   
zTFFunnelDecoder.buildr	  rR   r   r+   r+   r;   r=   r    s    
-r  c                      d   e Zd ZdZeZ fddZdd Zdd Zdd	 Z	e
	
	
	
	
	
	
	
	dddZdddZ  ZS )TFFunnelBaseLayerzBase model without decoderc                   sP   t  jdi | || _|j| _|j| _|j| _t|dd| _t	|dd| _
d S )N
embeddingsr   encoderr+   )r,   r-   r.   r   r  use_return_dictr  r%   r  r   r  r8   r;   r+   r=   r-     s   zTFFunnelBaseLayer.__init__c                 C     | j S rR   r  r9   r+   r+   r=   get_input_embeddings!     z&TFFunnelBaseLayer.get_input_embeddingsc                 C     || j _t|d | j _d S Nr   r  r>   r   rE   r9   r|   r+   r+   r=   set_input_embeddings$     z&TFFunnelBaseLayer.set_input_embeddingsc                 C     t rR   r   r9   Zheads_to_pruner+   r+   r=   _prune_heads(     zTFFunnelBaseLayer._prune_headsNFc	              	   C  s   |d ur|d urt d|d urt|}	n|d ur"t|d d }	nt d|d u r0t|	d}|d u r:t|	d}|d u rE| j||d}| j|||||||d}
|
S )NDYou cannot specify both input_ids and inputs_embeds at the same timert   5You have to specify either input_ids or inputs_embedsr#   r   rf   rn   ro   r   r  r  rM   )
ValueErrorr   rB   r   r  r  )r9   rO   rn   ro   rP   r   r  r  rM   rK   encoder_outputsr+   r+   r=   rQ   +  s.   

zTFFunnelBaseLayer.callc                 C  r   )NTr  r  )rF   rG   rB   rC   r  r*   rH   r  rJ   r+   r+   r=   rH   U  r   zTFFunnelBaseLayer.buildNNNNNNNFrR   rT   rU   rV   rW   r$   config_classr-   r  r  r$  r   rQ   rH   rX   r+   r+   r;   r=   r    s$    )r  c                      r  )TFFunnelMainLayerzBase model with decoderc                   sf   t  jdi | || _|j| _|j| _|j| _|j| _t|dd| _	t
|dd| _t|dd| _d S )Nr  r   r  decoderr+   )r,   r-   r.   r   r   r  r  r  r%   r  r   r  r  r/  r8   r;   r+   r=   r-   g  s   zTFFunnelMainLayer.__init__c                 C  r  rR   r  r  r+   r+   r=   r  t  r  z&TFFunnelMainLayer.get_input_embeddingsc                 C  r  r  r  r  r+   r+   r=   r  w  r   z&TFFunnelMainLayer.set_input_embeddingsc                 C  r!  rR   r"  r#  r+   r+   r=   r$  {  r%  zTFFunnelMainLayer._prune_headsNFc	              
   C  s^  |d ur|d urt d|d urt|}	n|d ur"t|d d }	nt d|d u r0t|	d}|d u r:t|	d}|d u rE| j||d}| j||||d||d}
| j|
d |
d | jd  ||||||d	}|sd}|d f}|r|d7 }||
d ||  f }|r|d7 }||
d
 ||  f }|S t|d |r|
j	|j	 nd |r|
j
|j
 dS d dS )Nr&  rt   r'  r#   r   rf   Tr(  )r  r  rn   ro   r   r  r  rM   rZ   r   )r)  r   rB   r   r  r  r/  r   r	   r   r   )r9   rO   rn   ro   rP   r   r  r  rM   rK   r*  Zdecoder_outputsidxoutputsr+   r+   r=   rQ   ~  sf   


zTFFunnelMainLayer.callc                 C  s   | j rd S d| _ t| dd d ur-t| jj | jd  W d    n1 s(w   Y  t| dd d urRt| jj | jd  W d    n1 sMw   Y  t| dd d urzt| jj | jd  W d    d S 1 ssw   Y  d S d S )NTr  r  r/  )	rF   rG   rB   rC   r  r*   rH   r  r/  rJ   r+   r+   r=   rH     s    "zTFFunnelMainLayer.buildr+  rR   r,  r+   r+   r;   r=   r.  a  s$    Er.  c                      s2   e Zd ZdZ fddZdd Zd	ddZ  ZS )
 TFFunnelDiscriminatorPredictionszEPrediction module for the discriminator, made up of two dense layers.c                   s\   t  jdi | t|j}tjj|j|dd| _t	|j
| _tjjd|dd| _|| _d S )Ndenser   r#   dense_predictionr+   )r,   r-   r   r?   r   r1   r   rI   r3  r   r   r   r4  r.   r   r;   r+   r=   r-     s   

z)TFFunnelDiscriminatorPredictions.__init__c                 C  s(   |  |}| |}t| |}|S rR   )r3  r   rB   r   r4  )r9   discriminator_hidden_statesr   logitsr+   r+   r=   rQ     s   

z%TFFunnelDiscriminatorPredictions.callNc                 C     | j rd S d| _ t| dd d ur2t| jj | jd d | jjg W d    n1 s-w   Y  t| dd d ur_t| j	j | j	d d | jjg W d    d S 1 sXw   Y  d S d S )NTr3  r4  )
rF   rG   rB   rC   r3  r*   rH   r.   rI   r4  rJ   r+   r+   r=   rH        "z&TFFunnelDiscriminatorPredictions.buildrR   )rT   rU   rV   rW   r-   rQ   rH   rX   r+   r+   r;   r=   r2    s
    r2  c                      sR   e Zd Z fddZ fddZdd Zdd Zd	d
 Zdd ZdddZ	  Z
S )TFFunnelMaskedLMHeadc                   s*   t  jdi | || _|j| _|| _d S )Nr+   )r,   r-   r.   r/   input_embeddings)r9   r.   r:  r:   r;   r+   r=   r-     s   
zTFFunnelMaskedLMHead.__init__c                   s*   | j | jjfdddd| _t | d S )Nr  Tbiasr   )rD   r.   rE   r;  r,   rH   rJ   r;   r+   r=   rH     s   zTFFunnelMaskedLMHead.buildc                 C  r  rR   )r:  r  r+   r+   r=   get_output_embeddings  r  z*TFFunnelMaskedLMHead.get_output_embeddingsc                 C  r  r  )r:  r>   r   rE   r  r+   r+   r=   set_output_embeddings  r   z*TFFunnelMaskedLMHead.set_output_embeddingsc                 C  s
   d| j iS )Nr;  )r;  r  r+   r+   r=   get_bias  s   
zTFFunnelMaskedLMHead.get_biasc                 C  s"   |d | _ t|d d | j_d S )Nr;  r   )r;  r   r.   rE   r  r+   r+   r=   set_bias  s   
zTFFunnelMaskedLMHead.set_biasFc                 C  sd   t |dd }tj|d| jgd}tj|| jjdd}tj|d|| jjgd}tj	j
|| jd}|S )N)r   r#   rt   )r   r@   T)abZtranspose_b)r|   r;  )r   rB   r   r/   matmulr:  r>   r.   rE   r   Zbias_addr;  )r9   r   rM   
seq_lengthr+   r+   r=   rQ   
  s   zTFFunnelMaskedLMHead.callr   )rT   rU   rV   r-   rH   r<  r=  r>  r?  rQ   rX   r+   r+   r;   r=   r9    s    r9  c                      r   )TFFunnelClassificationHeadc                   s`   t  jdi | t|j}tjj|j|dd| _tj	|j
| _tjj||dd| _|| _d S )Nlinear_hiddenr   
linear_outr+   )r,   r-   r   r?   r   r1   r   rI   rE  r5   r6   r7   rF  r.   )r9   r.   Zn_labelsr:   rA   r;   r+   r=   r-     s   

z#TFFunnelClassificationHead.__init__Fc                 C  s.   |  |}tj|}| j||d}| |S r   )rE  r   Zactivationstanhr7   rF  )r9   r   rM   r+   r+   r=   rQ     s   

zTFFunnelClassificationHead.callNc                 C  r7  )NTrE  rF  )
rF   rG   rB   rC   rE  r*   rH   r.   rI   rF  rJ   r+   r+   r=   rH   #  r8  z TFFunnelClassificationHead.buildr   rR   r   r+   r+   r;   r=   rD    s    
rD  c                   @  s$   e Zd ZdZeZdZedd ZdS )TFFunnelPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    funnelc                 C     dt jdt jdiS )NrO   )r#   r   rg   rB   rm   Zint32r  r+   r+   r=   dummy_inputs8     z$TFFunnelPreTrainedModel.dummy_inputsN)	rT   rU   rV   rW   r$   r-  Zbase_model_prefixpropertyrL  r+   r+   r+   r=   rH  /  s    rH  c                   @  s6   e Zd ZU dZdZded< dZded< dZded< dS )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Optional[tf.Tensor]r6  zTuple[tf.Tensor] | Noner   r   )rT   rU   rV   rW   r6  r   r   r   r+   r+   r+   r=   rO  >  s
   
 rO  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                      sl   e Zd Zd fddZeededee	d	e
	
	
	
	
	
	
	
	d d!ddZdd Zd"ddZ  ZS )#TFFunnelBaseModelr.   r$   returnNonec                   ,   t  j|g|R i | t|dd| _d S NrI  r   )r,   r-   r  rI  r9   r.   rL   r:   r;   r+   r=   r-        zTFFunnelBaseModel.__init__batch_size, sequence_lengthfunnel-transformer/small-base
checkpointoutput_typer-  NFrO   TFModelInputType | Nonern   np.ndarray | tf.Tensor | Nonero   rP   r   Optional[bool]r  r  rM   bool*Union[Tuple[tf.Tensor], TFBaseModelOutput]c	           	   
   C     | j ||||||||dS N)rO   rn   ro   rP   r   r  r  rM   rI  	r9   rO   rn   ro   rP   r   r  r  rM   r+   r+   r=   rQ        zTFFunnelBaseModel.callc                 C     t |j|j|jdS Nr   r	   r   r   r   r9   r   r+   r+   r=   serving_output  
   z TFFunnelBaseModel.serving_outputc                 C  d   | j rd S d| _ t| dd d ur0t| jj | jd  W d    d S 1 s)w   Y  d S d S NTrI  rF   rG   rB   rC   rI  r*   rH   rJ   r+   r+   r=   rH        "zTFFunnelBaseModel.buildr.   r$   rQ  rR  r+  rO   r\  rn   r]  ro   r]  rP   r]  r   r^  r  r^  r  r^  rM   r_  rQ  r`  rR   )rT   rU   rV   r-   r    FUNNEL_INPUTS_DOCSTRINGformatr   r	   _CONFIG_FOR_DOCr   rQ   rj  rH   rX   r+   r+   r;   r=   rP    s(    	rP  zlThe bare Funnel Transformer Model transformer outputting raw hidden-states without any specific head on top.c                      sl   e Zd Zd fddZeeedede	e
d		
	
	
	
	
	
	
	d d!ddZdd Zd"ddZ  ZS )#TFFunnelModelr.   r$   rQ  rR  c                   rS  rT  )r,   r-   r.  rI  rU  r;   r+   r=   r-     rV  zTFFunnelModel.__init__rW  funnel-transformer/smallrY  NFrO   r\  rn   r]  ro   rP   r   r^  r  r  rM   r_  r`  c	           	   
   C  ra  rb  rc  rd  r+   r+   r=   rQ     re  zTFFunnelModel.callc                 C  rf  rg  rh  ri  r+   r+   r=   rj    rk  zTFFunnelModel.serving_outputc                 C  rl  rm  rn  rJ   r+   r+   r=   rH     ro  zTFFunnelModel.buildrp  r+  rq  rR   )rT   rU   rV   r-   r   r    rr  rs  r   r	   rt  rQ   rj  rH   rX   r+   r+   r;   r=   ru    s(    	ru  z|
    Funnel model with a binary classification head on top as used during pretraining for identifying generated tokens.
    c                      sj   e Zd Zd fddZeeedee	e
d															
dd ddZdd Zd!ddZ  ZS )"TFFunnelForPreTrainingr.   r$   rQ  rR  c                   s4   t  j|fi | t|dd| _t|dd| _d S )NrI  r   discriminator_predictions)r,   r-   r.  rI  r2  rx  r8   r;   r+   r=   r-   ,  s   zTFFunnelForPreTraining.__init__rW  )r[  r-  NFrO   r\  rn   r]  ro   rP   r   r^  r  r  rM   r_  5Union[Tuple[tf.Tensor], TFFunnelForPreTrainingOutput]c	              
   K  sT   | j ||||||||d}
|
d }| |}|s!|f|
dd  S t||
j|
jd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
        ```r  rM   r   r#   Nr6  r   r   )rI  rx  rO  r   r   )r9   rO   rn   ro   rP   r   r  r  rM   r:   r5  Zdiscriminator_sequence_outputr6  r+   r+   r=   rQ   2  s&   

zTFFunnelForPreTraining.callc                 C  rf  Nr{  )rO  r6  r   r   ri  r+   r+   r=   rj  f     z%TFFunnelForPreTraining.serving_outputc                 C  r   )NTrI  rx  )rF   rG   rB   rC   rI  r*   rH   rx  rJ   r+   r+   r=   rH   m  r   zTFFunnelForPreTraining.buildrp  r+  )rO   r\  rn   r]  ro   r]  rP   r]  r   r^  r  r^  r  r^  rM   r_  rQ  ry  rR   )rT   rU   rV   r-   r   r    rr  rs  r"   rO  rt  rQ   rj  rH   rX   r+   r+   r;   r=   rw  %  s     
1rw  z4Funnel Model with a `language modeling` head on top.c                      s   e Zd Zd( fddZd)dd	Zd*ddZeee	de
deed									d+d,d d!Zd-d$d%Zd.d&d'Z  ZS )/TFFunnelForMaskedLMr.   r$   rQ  rR  c                   s@   t  j|g|R i | t|dd| _t|| jjdd| _d S )NrI  r   lm_head)r,   r-   r.  rI  r9  r  r  rU  r;   r+   r=   r-   {  s   zTFFunnelForMaskedLM.__init__r9  c                 C  r  rR   )r  r  r+   r+   r=   get_lm_head  r  zTFFunnelForMaskedLM.get_lm_headstrc                 C  s   t dt | jd | jj S )NzMThe method get_prefix_bias_name is deprecated. Please use `get_bias` instead./)warningswarnFutureWarningr*   r  r  r+   r+   r=   get_prefix_bias_name  s   z(TFFunnelForMaskedLM.get_prefix_bias_namerW  rv  rY  NFrO   r\  rn   r]  ro   rP   r   r^  r  r  labelsrM   r_  )Union[Tuple[tf.Tensor], TFMaskedLMOutput]c
              
   C  s   | j ||||||||	d}
|
d }| j||	d}|du rdn| ||}|s:|f|
dd  }|dur8|f| S |S t|||
j|
jd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]`
        rz  r   rf   Nr#   lossr6  r   r   )rI  r  hf_compute_lossr
   r   r   )r9   rO   rn   ro   rP   r   r  r  r  rM   r1  sequence_outputZprediction_scoresr  r   r+   r+   r=   rQ     s,   
zTFFunnelForMaskedLM.callr   r
   c                 C  rf  r|  )r
   r6  r   r   ri  r+   r+   r=   rj    rM  z"TFFunnelForMaskedLM.serving_outputc                 C  r   )NTrI  r  )rF   rG   rB   rC   rI  r*   rH   r  rJ   r+   r+   r=   rH     r   zTFFunnelForMaskedLM.buildrp  )rQ  r9  )rQ  r  	NNNNNNNNF)rO   r\  rn   r]  ro   r]  rP   r]  r   r^  r  r^  r  r^  r  r]  rM   r_  rQ  r  )r   r
   rQ  r
   rR   )rT   rU   rV   r-   r  r  r   r    rr  rs  r   r
   rt  rQ   rj  rH   rX   r+   r+   r;   r=   r~  y  s.    


,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                      p   e Zd Zd" fddZeeedede	e
d		
	
	
	
	
	
	
	
	d#d$ddZd%ddZd&d d!Z  ZS )'!TFFunnelForSequenceClassificationr.   r$   rQ  rR  c                   sF   t  j|g|R i | |j| _t|dd| _t||jdd| _d S )NrI  r   
classifier)r,   r-   
num_labelsr  rI  rD  r  rU  r;   r+   r=   r-     s   z*TFFunnelForSequenceClassification.__init__rW  rX  rY  NFrO   r\  rn   r]  ro   rP   r   r^  r  r  r  rM   r_  3Union[Tuple[tf.Tensor], TFSequenceClassifierOutput]c
              
   C  s   | j ||||||||	d}
|
d }|dddf }| j||	d}|du r&dn| ||}|sB|f|
dd  }|dur@|f| S |S t|||
j|
jd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).
        rz  r   Nrf   r#   r  )rI  r  r  r   r   r   )r9   rO   rn   ro   rP   r   r  r  r  rM   r1  r   pooled_outputr6  r  r   r+   r+   r=   rQ     s.   
z&TFFunnelForSequenceClassification.callr   r   c                 C  rf  r|  )r   r6  r   r   ri  r+   r+   r=   rj    r}  z0TFFunnelForSequenceClassification.serving_outputc                 C  r   NTrI  r  rF   rG   rB   rC   rI  r*   rH   r  rJ   r+   r+   r=   rH     r   z'TFFunnelForSequenceClassification.buildrp  r  )rO   r\  rn   r]  ro   r]  rP   r]  r   r^  r  r^  r  r^  r  r]  rM   r_  rQ  r  )r   r   rQ  r   rR   )rT   rU   rV   r-   r   r    rr  rs  r   r   rt  rQ   rj  rH   rX   r+   r+   r;   r=   r    s*    
-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                      s|   e Zd Zd$ fddZedd Zeee	d	e
d
eed									d%d&ddZd'd d!Zd(d"d#Z  ZS ))TFFunnelForMultipleChoicer.   r$   rQ  rR  c                   s<   t  j|g|R i | t|dd| _t|ddd| _d S )NrI  r   r#   r  )r,   r-   r  rI  rD  r  rU  r;   r+   r=   r-   *  s   z"TFFunnelForMultipleChoice.__init__c                 C  rJ  )NrO   )r   r      rg   rK  r  r+   r+   r=   rL  0  s   z&TFFunnelForMultipleChoice.dummy_inputsz(batch_size, num_choices, sequence_lengthrX  rY  NFrO   r\  rn   r]  ro   rP   r   r^  r  r  r  rM   r_  4Union[Tuple[tf.Tensor], TFMultipleChoiceModelOutput]c
              
   C  s\  |durt |d }
t |d }nt |d }
t |d }|dur)t|d|fnd}|dur7t|d|fnd}|durEt|d|fnd}|durXt|d|t |d fnd}| j||||||||	d}|d }|dddf }| j||	d}t|d|
f}|du rdn| ||}|s|f|dd  }|dur|f| S |S t|||j|jd	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#   rZ   rt   r   )rn   ro   rP   r   r  r  rM   r   rf   r  )	r   rB   r   rI  r  r  r   r   r   )r9   rO   rn   ro   rP   r   r  r  r  rM   Znum_choicesrC  Zflat_input_idsZflat_attention_maskZflat_token_type_idsZflat_inputs_embedsr1  r   r  r6  Zreshaped_logitsr  r   r+   r+   r=   rQ   4  sH   zTFFunnelForMultipleChoice.callr   r   c                 C  rf  r|  )r   r6  r   r   ri  r+   r+   r=   rj  y  r}  z(TFFunnelForMultipleChoice.serving_outputc                 C  r   r  r  rJ   r+   r+   r=   rH     r   zTFFunnelForMultipleChoice.buildrp  r  )rO   r\  rn   r]  ro   r]  rP   r]  r   r^  r  r^  r  r^  r  r]  rM   r_  rQ  r  )r   r   rQ  r   rR   )rT   rU   rV   r-   rN  rL  r   r    rr  rs  r   r   rt  rQ   rj  rH   rX   r+   r+   r;   r=   r  "  s.    

>r  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                      r  )'TFFunnelForTokenClassificationr.   r$   rQ  rR  c                   sf   t  j|g|R i | |j| _t|dd| _tj|j| _	tjj
|jt|jdd| _|| _d S )NrI  r   r  r   )r,   r-   r  r.  rI  r   r1   r5   r6   r7   r   r   r?   r  r.   rU  r;   r+   r=   r-     s   
z'TFFunnelForTokenClassification.__init__rW  rv  rY  NFrO   r\  rn   r]  ro   rP   r   r^  r  r  r  rM   r_  0Union[Tuple[tf.Tensor], TFTokenClassifierOutput]c
              
   C  s   | j ||||||||	d}
|
d }| j||	d}| |}|du r#dn| ||}|s?|f|
dd  }|dur=|f| S |S t|||
j|
jd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]`.
        rz  r   rf   Nr#   r  )rI  r7   r  r  r   r   r   )r9   rO   rn   ro   rP   r   r  r  r  rM   r1  r  r6  r  r   r+   r+   r=   rQ     s.   

z#TFFunnelForTokenClassification.callr   r   c                 C  rf  r|  )r   r6  r   r   ri  r+   r+   r=   rj    r}  z-TFFunnelForTokenClassification.serving_outputc                 C     | j rd S d| _ t| dd d ur-t| jj | jd  W d    n1 s(w   Y  t| dd d urZt| jj | jd d | jj	g W d    d S 1 sSw   Y  d S d S r  )
rF   rG   rB   rC   rI  r*   rH   r  r.   r/   rJ   r+   r+   r=   rH        "z$TFFunnelForTokenClassification.buildrp  r  )rO   r\  rn   r]  ro   r]  rP   r]  r   r^  r  r^  r  r^  r  r]  rM   r_  rQ  r  )r   r   rQ  r   rR   )rT   rU   rV   r-   r   r    rr  rs  r   r   rt  rQ   rj  rH   rX   r+   r+   r;   r=   r    s*    
,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                      sr   e Zd Zd# fddZeeedede	e
d		
	
	
	
	
	
	
	
	
	d$d%ddZd&dd Zd'd!d"Z  ZS )(TFFunnelForQuestionAnsweringr.   r$   rQ  rR  c                   sV   t  j|g|R i | |j| _t|dd| _tjj|jt|j	dd| _
|| _d S )NrI  r   
qa_outputsr   )r,   r-   r  r.  rI  r   r1   r   r   r?   r  r.   rU  r;   r+   r=   r-     s   
z%TFFunnelForQuestionAnswering.__init__rW  rv  rY  NFrO   r\  rn   r]  ro   rP   r   r^  r  r  start_positionsend_positionsrM   r_  7Union[Tuple[tf.Tensor], TFQuestionAnsweringModelOutput]c              
   C  s   | j ||||||||
d}|d }| |}tj|ddd\}}tj|dd}tj|dd}d}|durE|	durE||	d}| |||f}|s\||f|dd  }|durZ|f| S |S t||||j|jd	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.
        rz  r   rZ   rt   rz   N)Zstart_positionZend_positionr#   )r  start_logits
end_logitsr   r   )	rI  r  rB   r   r   r  r   r   r   )r9   rO   rn   ro   rP   r   r  r  r  r  rM   r1  r  r6  r  r  r  r  r   r+   r+   r=   rQ     s:   


z!TFFunnelForQuestionAnswering.callr   r   c                 C  s   t |j|j|j|jdS )N)r  r  r   r   )r   r  r  r   r   ri  r+   r+   r=   rj  8  s   z+TFFunnelForQuestionAnswering.serving_outputc                 C  r  )NTrI  r  )
rF   rG   rB   rC   rI  r*   rH   r  r.   r/   rJ   r+   r+   r=   rH   B  r  z"TFFunnelForQuestionAnswering.buildrp  )
NNNNNNNNNF)rO   r\  rn   r]  ro   r]  rP   r]  r   r^  r  r^  r  r^  r  r]  r  r]  rM   r_  rQ  r  )r   r   rQ  r   rR   )rT   rU   rV   r-   r   r    rr  rs  r   r   rt  rQ   rj  rH   rX   r+   r+   r;   r=   r    s,    

:
r  )	rP  r~  r  rw  r  r  r  ru  rH  )TF)RrW   
__future__r   r  dataclassesr   typingr   r   r   numpynpZ
tensorflowrB   Zactivations_tfr   Zmodeling_tf_outputsr	   r
   r   r   r   r   Zmodeling_tf_utilsr   r   r   r   r   r   r   r   r   r   r   Ztf_utilsr   r   r   utilsr   r   r   r    r!   r"   Zconfiguration_funnelr$   Z
get_loggerrT   loggerrt  r   r1   ZLayerr%   rY   r   r   r   r   r   r  r  r  r.  r2  r9  rD  rH  rO  ZFUNNEL_START_DOCSTRINGrr  rP  ru  rw  r~  r  r  r  r  __all__r+   r+   r+   r=   <module>   s    4 
0 w 8#
O@Pq$--44NROcRb