
    sgd                   h   d Z ddl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 ddlZddlZddlmZ ddl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 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)jZ                  e.      Z/ e(       r#	 ddl0Z1e1jd                  jg                  dd      Z4n"	 ddl0Z1e1jd                  jg                  dd      Z7dZ8dZ9dZ:dZ;e G d de%             Z< G d dejz                  j|                        Z? G d dejz                  j|                        Z@ G d dejz                  j|                        ZA G d dejz                  j|                        ZB G d  d!ejz                  j|                        ZC G d" d#ejz                  j|                        ZD G d$ d%ejz                  j|                        ZE G d& d'ejz                  j|                        ZF G d( d)ejz                  j|                        ZG G d* d+ejz                  j|                        ZH G d, d-ejz                  j|                        ZI G d. d/ejz                  j|                        ZJe G d0 d1ejz                  j|                               ZK G d2 d3e      ZLd4ZMd5ZN e&d6eM       G d7 d8eL             ZO e&d9eM       G d: d;eLe             ZP G d< d=ejz                  j|                        ZQ G d> d?ejz                  j|                        ZR e&d@eM       G dA dBeL             ZS e&dCeM       G dD dEeLe             ZT	  G dF dGeUej                        ZW G dH dI      ZX G dJ dKeX      ZYd[dLZZd\dMZ[d]dNZ\dO Z]d^dPZ^d_dQZ_d`dRZ`dadSZadT ZbdU ZcdV ZddW ZedX ZfdY ZgdZ Zhy# e5$ r e/jm                  d       Y w xY w# e5$ r Y w xY w)bzTF 2.0 TAPAS model.    )annotationsN)	dataclass)DictOptionalTupleUnion   )get_tf_activation)+TFBaseModelOutputWithPastAndCrossAttentionsTFBaseModelOutputWithPoolingTFMaskedLMOutputTFSequenceClassifierOutput)TFMaskedLanguageModelingLossTFModelInputTypeTFPreTrainedModelTFSequenceClassificationLossget_initializerkeraskeras_serializableunpack_inputs)check_embeddings_within_bounds
shape_liststable_softmax)ModelOutputadd_start_docstrings%add_start_docstrings_to_model_forward#is_tensorflow_probability_availableloggingreplace_return_docstrings   )TapasConfigg              ?)locscalea
  TAPAS models are not usable since `tensorflow_probability` can't be loaded. It seems you have `tensorflow_probability` installed with the wrong tensorflow version. Please try to reinstall it following the instructions here: https://github.com/tensorflow/probability.r!   zgoogle/tapas-baseg|=     c                  X    e Zd ZU dZdZded<   dZded<   dZded<   dZded	<   dZ	ded
<   y)TFTableQuestionAnsweringOutputa[  
    Output type of [`TFTapasForQuestionAnswering`].

    Args:
        loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` (and possibly `answer`, `aggregation_labels`, `numeric_values` and `numeric_values_scale` are provided)):
            Total loss as the sum of the hierarchical cell selection log-likelihood loss and (optionally) the
            semi-supervised regression loss and (optionally) supervised loss for aggregations.
        logits (`tf.Tensor` of shape `(batch_size, sequence_length)`):
            Prediction scores of the cell selection head, for every token.
        logits_aggregation (`tf.Tensor`, *optional*, of shape `(batch_size, num_aggregation_labels)`):
            Prediction scores of the aggregation head, for every aggregation operator.
        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.
    Ntf.Tensor | Noneloss	tf.Tensorlogitslogits_aggregationTuple[tf.Tensor] | Nonehidden_states
attentions)
__name__
__module____qualname____doc__r)   __annotations__r+   r,   r.   r/        ^/var/www/html/venv/lib/python3.12/site-packages/transformers/models/tapas/modeling_tf_tapas.pyr'   r'   Z   s@    * "D
!FI+/(/-1M*1*.J'.r6   r'   c                  V     e Zd ZdZd fdZddZ	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZ xZS )	TFTapasEmbeddingsz
    Construct the embeddings from word, position and token_type embeddings. Same as BertEmbeddings but with a number of
    additional token type embeddings to encode tabular structure.
    c                   t        |   di | || _        t        |j                        | _        |j                  | _        |j                  | _        |j                  | _        |j                  | _	        t        j                  j                  |j                  d      | _        t        j                  j                  |j                         | _        y )N	LayerNormepsilonnamerater5   )super__init__configlentype_vocab_sizesnumber_of_token_type_embeddingsreset_position_index_per_cellhidden_sizemax_position_embeddingsinitializer_ranger   layersLayerNormalizationlayer_norm_epsr;   Dropouthidden_dropout_probdropoutselfrC   kwargs	__class__s      r7   rB   zTFTapasEmbeddings.__init__~   s    "6"/263J3J/K,-3-Q-Q*!--'-'E'E$!'!9!988AVAV]h8i||++1K1K+Lr6   c                   t        j                  d      5  | j                  d| j                  j                  | j
                  gt        | j                              | _        d d d        t        j                  d      5  | j                  d| j                  | j
                  gt        | j                              | _
        d d d        t        | j                  j                        D ]g  \  }}t        j                  d|       5  t        | d| | j                  d|| j
                  gt        | j                                     d d d        i | 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   zxY w# 1 sw Y   'xY w# 1 sw Y   xY w# 1 sw Y   y xY w)	Nword_embeddingsweight)r>   shapeinitializerposition_embeddings
embeddingstoken_type_embeddings_Tr;   )tf
name_scope
add_weightrC   
vocab_sizerH   r   rJ   rW   rI   rZ   	enumeraterE   setattrbuiltgetattrr;   r>   build)rR   input_shapeitype_vocab_sizes       r7   re   zTFTapasEmbeddings.build   s   ]],- 	//{{--t/?/?@+D,B,BC * DK	 ]]01 	'+!33T5E5EF+D,B,BC (7 (D$	 #,DKK,H,H"I 
	A!7s;< 	,QC0OO).0@0@A$3D4J4J$K $ 	 	
	 ::
4d+7t~~223 L$$dD$++2I2I%JKL L 89	 		 		 	L Ls2   AG AG(AG53HG%(G25G?	Hc           	        ||J |t        |      }nt        |      dd }|d   }|%t        j                  || j                  gz   d      }|0t        j                  t        j
                  d|      d      }t        j                  ||      }| j                  rt        |dddddf   | j                  j                  d   d	      }t        |ddddd
f   | j                  j                  d
   d	      }	t        ||	      }
t        ||
      d   }t        ||
      }t        j                  t        j
                  d|      d      }t        j                  j                  | j                   dz
  ||z
        }|At#        || j                  j$                         t        j                  | j&                  |      }t        j                  | j(                  |      }||z   }t        | j                        D ]5  }d| }|t        j                  t+        | |      |dddd|f         z  }7 | j-                  |      }| j/                  ||      }|S )z
        Applies embedding based on inputs tensor.

        Returns:
            final_embeddings (`tf.Tensor`): output embedding tensor.
        Nr    r   dimsvalue)startlimitaxis)rX   )
batch_dims   )paramsindices)ru   r\   inputsrw   training)r   r]   fillrF   expand_dimsrangebroadcast_torG   IndexMaprC   rE   ProductIndexMap
reduce_mingathermathminimumrI   r   r`   rW   rZ   rd   r;   rP   )rR   	input_idsposition_idstoken_type_idsinputs_embedsry   rf   
seq_length	col_index	row_index
full_indexfirst_position_per_segmentfirst_positionpositionrZ   final_embeddingsrg   r>   s                     r7   callzTFTapasEmbeddings.call   s4    %-*?@@ $Y/K$]3CR8K ^
!WW+9]9]8^*^fghN>>"((**MTUVL??<{KL11$^Aq!G%<dkk>Z>Z[\>]jkl	$^Aq!G%<dkk>Z>Z[\>]jkl	,Y	B
-7j-QRS-T*!'(BJ!O>>"((**MTUV!wwt/K/Ka/OQY\jQjk *9dkk6L6LMIIT[[)LM ii(@(@,W(+>>t;;< 	gA+A3/D		t1Dn]^`acd]dNe ff	g  >>1A>B<</?(<Sr6   rC   r!   N)NNNNF)r   r*   r   r*   r   r*   r   r*   ry   boolreturnr*   )r0   r1   r2   r3   rB   re   r   __classcell__rT   s   @r7   r9   r9   x   se    

MLF  $"&$(#'< <   <  "	< 
 !<  <  
< r6   r9   c                  ^     e Zd Zd fdZddZ	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZd	dZ xZS )
TFTapasSelfAttentionc                   t        |   d
i | |j                  |j                  z  dk7  r&t	        d|j                   d|j                   d      |j                  | _        t        |j                  |j                  z        | _        | j                  | j                  z  | _        t        j                  | j                        | _
        t        j                  j                  | j                  t        |j                        d      | _        t        j                  j                  | j                  t        |j                        d      | _        t        j                  j                  | j                  t        |j                        d      | _        t        j                  j'                  |j(                  	      | _        |j,                  | _        || _        y )Nr   zThe hidden size (z6) is not a multiple of the number of attention heads ()queryunitskernel_initializerr>   keyrm   r?   r5   )rA   rB   rH   num_attention_heads
ValueErrorintattention_head_sizeall_head_sizer   sqrtsqrt_att_head_sizer   rK   Denser   rJ   r   r   rm   rN   attention_probs_dropout_probrP   
is_decoderrC   rQ   s      r7   rB   zTFTapasSelfAttention.__init__   s   "6" : ::a?#F$6$6#7 8''-'A'A&B!E 
 $*#=#= #&v'9'9F<V<V'V#W !558P8PP"&))D,D,D"E\\''$$IaIa9bip ( 

 <<%%$$IaIa9bin & 
 \\''$$IaIa9bip ( 

 ||++1T1T+U ++r6   c                    t        j                  ||d| j                  | j                  f      }t        j                  |g d      S )Nrj   tensorrX   r   rs   r    r	   perm)r]   reshaper   r   	transpose)rR   r   
batch_sizes      r7   transpose_for_scoresz)TFTapasSelfAttention.transpose_for_scores  s;    6*b$BZBZ\`\t\t1uv ||F66r6   c	                   t        |      d   }	| j                  |      }
|d u}|r||d   }|d   }|}n|rG| j                  | j                  |      |	      }| j                  | j	                  |      |	      }|}n|}| j                  | j                  |      |	      }| j                  | j	                  |      |	      }t        j                  |d   |gd      }t        j                  |d   |gd      }nD| j                  | j                  |      |	      }| j                  | j	                  |      |	      }| j                  |
|	      }| j                  r||f}t        j                  ||d      }t        j                  | j                  |j                        }t        j                  ||      }|t        j                  ||      }t        |d	
      }| j                  ||      }|t        j                   ||      }t        j                  ||      }t        j"                  |g d      }t        j$                  ||	d	| j&                  f      }|r||fn|f}| j                  r||fz   }|S )Nr   rv   r    rs   rp   T)transpose_bdtyperj   )r+   rq   rx   r   r   r   )r   r   r   r   rm   r]   concatr   matmulcastr   r   divideaddr   rP   multiplyr   r   r   )rR   r.   attention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionsry   r   mixed_query_layeris_cross_attention	key_layervalue_layerquery_layerattention_scoresdkattention_probsattention_outputoutputss                       r7   r   zTFTapasSelfAttention.call  sy     .q1
 JJmJ<
 3$>."<&q)I(+K3N11$((BW(2XZdeI33DJJF[J4\^hiK3N'11$((-(2PR\]I33DJJmJ4TV`aK		>!#4i"@qII))^A%6$D1MK11$((-(2PR\]I33DJJmJ4TV`aK//0A:N?? (5N 99[)NWWT,,4D4J4JK99%5r:%!vv&6G )0@rJ ,,o,Q   kk/9EO99_kB<<(8|L ::-=jRTVZVhVhEij9J#_5QaPc?? 11Gr6   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   rm   )rc   rd   r]   r^   r   r>   re   rC   rH   r   rm   rR   rf   s     r7   re   zTFTapasSelfAttention.build`  s9   ::
4$'3tzz/ H

  $dkk.E.E!FGH4%1txx}}- FdDKK,C,CDEF4$'3tzz/ H

  $dkk.E.E!FGH H 4H HF FH Hs$   3E*<3E6-3F*E36E?Fr   )r   r*   r   r   r   r*   F)r.   r*   r   r*   r   r*   r   r*   r   r*   r   Tuple[tf.Tensor]r   r   ry   r   r   r   r   )r0   r1   r2   rB   r   r   re   r   r   s   @r7   r   r      s    87  O O "O 	O
  )O !*O )O  O O 
ObHr6   r   c                  2     e Zd Zd fdZdddZddZ xZS )TFTapasSelfOutputc                x   t        |   di | t        j                  j	                  |j
                  t        |j                        d      | _        t        j                  j                  |j                  d      | _        t        j                  j                  |j                        | _        || _        y Ndenser   r;   r<   r?   r5   rA   rB   r   rK   r   rH   r   rJ   r   rL   rM   r;   rN   rO   rP   rC   rQ   s      r7   rB   zTFTapasSelfOutput.__init__q      "6"\\''$$IaIa9bip ( 

 88AVAV]h8i||++1K1K+Lr6   c                z    | j                  |      }| j                  ||      }| j                  ||z         }|S Nrv   rx   r   rP   r;   rR   r.   input_tensorry   s       r7   r   zTFTapasSelfOutput.call{  ?    

-
8MHMml.JKr6   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;   
rc   rd   r]   r^   r   r>   re   rC   rH   r;   r   s     r7   re   zTFTapasSelfOutput.build      ::
4$'3tzz/ H

  $dkk.E.E!FGH4d+7t~~223 L$$dD$++2I2I%JKL L 8H HL L   3C9<3D9DDr   r   r.   r*   r   r*   ry   r   r   r*   r   r0   r1   r2   rB   r   re   r   r   s   @r7   r   r   p      	Lr6   r   c                  \     e Zd Zd fdZd Z	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZ xZS )	TFTapasAttentionc                l    t        |   di | t        |d      | _        t	        |d      | _        y )NrR   r>   outputr5   )rA   rB   r   self_attentionr   dense_outputrQ   s      r7   rB   zTFTapasAttention.__init__  s1    "6"26G-f8Dr6   c                    t         r   NotImplementedError)rR   headss     r7   prune_headszTFTapasAttention.prune_heads  s    !!r6   c	           
     x    | j                  ||||||||      }	| j                  |	d   ||      }
|
f|	dd  z   }|S )Nr.   r   r   r   r   r   r   ry   r   r.   r   ry   r    )r   r   )rR   r   r   r   r   r   r   r   ry   self_outputsr   r   s               r7   r   zTFTapasAttention.call  so     **&)"7#9)/ + 	
  ,,&q/x - 
 $%QR(88r6   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   )rc   rd   r]   r^   r   r>   re   r   r   s     r7   re   zTFTapasAttention.build  s    ::
4)40<t22778 0##))$/04.:t00556 .!!''-. . ;0 0. .   C%CCC r   r   )r   r*   r   r*   r   r*   r   r*   r   r*   r   r   r   r   ry   r   r   r   r   )r0   r1   r2   rB   r   r   re   r   r   s   @r7   r   r     su    E"  " 	
  ) !* )    
:	.r6   r   c                  0     e Zd Zd fdZddZddZ xZS )TFTapasIntermediatec                T   t        |   di | t        j                  j	                  |j
                  t        |j                        d      | _        t        |j                  t              r"t        |j                        | _        || _        y |j                  | _        || _        y )Nr   r   r5   )rA   rB   r   rK   r   intermediate_sizer   rJ   r   
isinstance
hidden_actstrr
   intermediate_act_fnrC   rQ   s      r7   rB   zTFTapasIntermediate.__init__  s    "6"\\''**vOgOg?hov ( 

 f''-'89J9J'KD$  (.'8'8D$r6   c                L    | j                  |      }| j                  |      }|S Nrv   )r   r   rR   r.   s     r7   r   zTFTapasIntermediate.call  s(    

-
800?r6   c                (   | 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   y xY wNTr   	rc   rd   r]   r^   r   r>   re   rC   rH   r   s     r7   re   zTFTapasIntermediate.build  }    ::
4$'3tzz/ H

  $dkk.E.E!FGH H 4H H   3BBr   r.   r*   r   r*   r   r   r   s   @r7   r   r     s    Hr6   r   c                  2     e Zd Zd fdZdddZddZ xZS )TFTapasOutputc                x   t        |   di | t        j                  j	                  |j
                  t        |j                        d      | _        t        j                  j                  |j                  d      | _        t        j                  j                  |j                        | _        || _        y r   r   rQ   s      r7   rB   zTFTapasOutput.__init__  r   r6   c                z    | j                  |      }| j                  ||      }| j                  ||z         }|S r   r   r   s       r7   r   zTFTapasOutput.call  r   r6   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r   )rc   rd   r]   r^   r   r>   re   rC   r   r;   rH   r   s     r7   re   zTFTapasOutput.build  s    ::
4$'3tzz/ N

  $dkk.K.K!LMN4d+7t~~223 L$$dD$++2I2I%JKL L 8N NL Lr   r   r   r   r   r   r   s   @r7   r  r    r   r6   r  c                  V     e Zd Zd fdZ	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZ xZS )TFTapasLayerc                D   t        |   di | t        |d      | _        |j                  | _        |j
                  | _        | j
                  r,| j                  st        |  d      t        |d      | _        t        |d      | _	        t        |d      | _        y )N	attentionr   z> should be used as a decoder model if cross attention is addedcrossattentionintermediater   r5   )rA   rB   r   r  r   add_cross_attentionr   r  r   r  r  bert_outputrQ   s      r7   rB   zTFTapasLayer.__init__  s    "6")&{C ++#)#=#= ##?? D6)g!hii"26@P"QD/^L(h?r6   c	           
        ||d d nd }	| j                  |||d d |	||      }
|
d   }| j                  r|
dd }|
d   }n|
dd  }d }| j                  rV|Tt        | d      st        d|  d      ||d	d  nd }| j	                  ||||||||      }|d   }||dd z   }|d   }|z   }| j                  |
      }| j                  |||      }|f|z   }| j                  r|fz   }|S )Nrs   )r   r   r   r   r   r   r   ry   r   r    rj   r  z'If `encoder_hidden_states` are passed, z` has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`r.   r   )r  r   hasattrr   r  r  r  )rR   r.   r   r   r   r   r   r   ry   self_attn_past_key_valueself_attention_outputsr   r   present_key_valuecross_attn_present_key_valuecross_attn_past_key_valuecross_attention_outputsintermediate_outputlayer_outputs                      r7   r   zTFTapasLayer.call  s    :H9S>"1#5Y] !%&)"&#'3/ "0 	"
 2!4 ??,Qr2G 6r :,QR0G'+$??4@4!12 =dV DD D  @N?Yrs(;_c%&*&9&9--#&;'=8"3! ': 	'#  7q9 7" ==G ,C2+F( 14P P"//>N/O''-<LW_ ( 
  /G+ ??!2 44Gr6   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       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   xY w# 1 sw Y   ~xY w# 1 sw Y   y xY w)NTr  r  r  r  )
rc   rd   r]   r^   r  r>   re   r  r  r  r   s     r7   re   zTFTapasLayer.buildU  sZ   ::
4d+7t~~223 +$$T*+4.:t00556 .!!''-.4-9t//445 -  &&t,-4)40<t22778 0##))$/0 0 =+ +. .- -0 0s0   E?%F?FF$?F	FF!$F-r   r   )r.   r*   r   r*   r   r*   r   r(   r   r(   r   r-   r   r   ry   r   r   r   r   r   r   s   @r7   r  r     s{    @, E E "E 	E
  0E !1E 0E  E E 
EN0r6   r  c                  b     e Zd Zd fdZ	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZ xZS )TFTapasEncoderc                    t        |   di | || _        t        |j                        D cg c]  }t        |d|        c}| _        y c c}w )Nzlayer_._r   r5   )rA   rB   rC   r|   num_hidden_layersr  layer)rR   rC   rS   rg   rT   s       r7   rB   zTFTapasEncoder.__init__i  sG    "6"INvOgOgIhiAl6(1#?i
is   Ac                   |	rdnd }|rdnd }|r| j                   j                  rdnd }|rdnd }t        | j                        D ]h  \  }}|	r||fz   }|||   nd } |||||   |||||      }|d   }|r	||d   fz  }|s=||d   fz   }| j                   j                  s]|`||d   fz   }j |	r||fz   }|
st	        d ||||fD              S t        |||||      S )	Nr5   r   r   rj   r    rs   c              3  &   K   | ]	  }||  y wr   r5   ).0vs     r7   	<genexpr>z&TFTapasEncoder.call.<locals>.<genexpr>  s      ghgts   )last_hidden_statepast_key_valuesr.   r/   cross_attentions)rC   r  ra   r(  tupler   )rR   r.   r   r   r   r   r/  	use_cacher   output_hidden_statesreturn_dictry   all_hidden_statesall_attentionsall_cross_attentionsnext_decoder_cacherg   layer_moduler   layer_outputss                       r7   r   zTFTapasEncoder.calln  sV    #7BD0d%64;;;Z;Zr`d#,R$(4 	VOA|#$58H$H!3B3N_Q/TXN(+-#A,&;'=-"3!	M *!,M"}R'8&::" !/=3C2E!E;;227L7X+?=QRCSBU+U(1	V6   1]4D D )+<nNbc   ;+.+%1
 	
r6   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)NTr(  )rc   rd   r(  r]   r^   r>   re   )rR   rf   r(  s      r7   re   zTFTapasEncoder.build  sp    ::
4$'3 &]]5::. &KK%& && 4& &s   A..A7	r   r   )r.   r*   r   r*   r   r*   r   r(   r   r(   r/  zTuple[Tuple[tf.Tensor]] | Noner2  Optional[bool]r   r   r3  r   r4  r   ry   r   r   zDUnion[TFBaseModelOutputWithPastAndCrossAttentions, Tuple[tf.Tensor]]r   r   r   s   @r7   r%  r%  h  s    j" <
 <
 "<
 	<

  0<
 !1<
 8<
 "<
  <
 #<
 <
 <
 
N<
|&r6   r%  c                  0     e Zd Zd fdZddZddZ xZS )TFTapasPoolerc                    t        |   di | t        j                  j	                  |j
                  t        |j                        dd      | _        || _	        y )Ntanhr   )r   r   
activationr>   r5   )
rA   rB   r   rK   r   rH   r   rJ   r   rC   rQ   s      r7   rB   zTFTapasPooler.__init__  sT    "6"\\''$$.v/G/GH	 ( 

 r6   c                <    |d d df   }| j                  |      }|S )Nr   rv   )r   )rR   r.   first_token_tensorpooled_outputs       r7   r   zTFTapasPooler.call  s*     +1a40

*<
=r6   c                (   | 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   y xY wr  r  r   s     r7   re   zTFTapasPooler.build  r  r  r   r	  r   r   r   s   @r7   r>  r>    s    	Hr6   r>  c                  0     e Zd Zd fdZddZddZ xZS )TFTapasPredictionHeadTransformc                   t        |   di | t        j                  j	                  |j
                  t        |j                        d      | _        t        |j                  t              rt        |j                        | _        n|j                  | _        t        j                  j                  |j                  d      | _        || _        y )Nr   r   r;   r<   r5   )rA   rB   r   rK   r   rH   r   rJ   r   r   r   r   r
   transform_act_fnrL   rM   r;   rC   rQ   s      r7   rB   z'TFTapasPredictionHeadTransform.__init__  s    "6"\\''$$.v/G/GH ( 

 f''-$5f6G6G$HD!$*$5$5D!88AVAV]h8ir6   c                p    | j                  |      }| j                  |      }| j                  |      }|S r  )r   rI  r;   r  s     r7   r   z#TFTapasPredictionHeadTransform.call  s8    

-
8--m<m<r6   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r   r   r   s     r7   re   z$TFTapasPredictionHeadTransform.build  r   r   r   r	  r   r   r   s   @r7   rG  rG    s    "	Lr6   rG  c                  P     e Zd Zd fdZd	dZd
dZddZddZddZddZ	 xZ
S )TFTapasLMPredictionHeadc                    t        |   di | || _        |j                  | _        t	        |d      | _        || _        y )N	transformr   r5   )rA   rB   rC   rH   rG  rO  input_embeddingsrR   rC   rP  rS   rT   s       r7   rB   z TFTapasLMPredictionHead.__init__  s@    "6"!--7[Q !1r6   c                X   | j                  | j                  j                  fddd      | _        | 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)NzerosTbias)rX   rY   	trainabler>   rO  )r_   rC   r`   rT  rc   rd   r]   r^   rO  r>   re   r   s     r7   re   zTFTapasLMPredictionHead.build  s    OO4;;+A+A*CQXdhouOv	::
4d+7t~~223 +$$T*+ + 8+ +s   :B  B)c                    | j                   S r   )rP  rR   s    r7   get_output_embeddingsz-TFTapasLMPredictionHead.get_output_embeddings  s    $$$r6   c                `    || j                   _        t        |      d   | j                   _        y Nr   )rP  rW   r   r`   rR   rm   s     r7   set_output_embeddingsz-TFTapasLMPredictionHead.set_output_embeddings  s(    ',$+5e+<Q+?(r6   c                    d| j                   iS )NrT  )rT  rW  s    r7   get_biasz TFTapasLMPredictionHead.get_bias  s    		""r6   c                X    |d   | _         t        |d         d   | j                  _        y )NrT  r   )rT  r   rC   r`   r[  s     r7   set_biasz TFTapasLMPredictionHead.set_bias  s'    &M	!+E&M!:1!=r6   c                   | j                  |      }t        |      d   }t        j                  |d| j                  g      }t        j
                  || j                  j                  d      }t        j                  |d|| j                  j                  g      }t        j                  j                  || j                        }|S )Nr  r    rj   r   T)abr   )rm   rT  )rO  r   r]   r   rH   r   rP  rW   rC   r`   nnbias_addrT  )rR   r.   r   s      r7   r   zTFTapasLMPredictionHead.call   s    ]C.q1


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

-JPTP[P[PfPf?gh]Kr6   rC   r!   rP  keras.layers.Layerr   r   rg  rm   ztf.Variable)r   zDict[str, tf.Variable]r	  )r0   r1   r2   rB   re   rX  r\  r^  r`  r   r   r   s   @r7   rM  rM    s'    
1+%@#>r6   rM  c                  0     e Zd Zd fdZddZddZ xZS )TFTapasMLMHeadc                J    t        |   di | t        ||d      | _        y )Npredictionsr   r5   )rA   rB   rM  rm  rQ  s       r7   rB   zTFTapasMLMHead.__init__-  s&    "6"26;KR_`r6   c                *    | j                  |      }|S )Nr  )rm  )rR   sequence_outputprediction_scoress      r7   r   zTFTapasMLMHead.call2  s     ,,?,K  r6   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)NTrm  )rc   rd   r]   r^   rm  r>   re   r   s     r7   re   zTFTapasMLMHead.build7  sm    ::
4-9t//445 -  &&t,- - :- -   A11A:rf  ro  r*   r   r*   r   r   r   s   @r7   rk  rk  ,  s    a
!
-r6   rk  c                       e Zd ZeZdd fdZd	dZd
dZd Ze		 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Z
ddZ xZS )TFTapasMainLayerc                    t        |   di | || _        t        |d      | _        t        |d      | _        |rt        |d      | _        y d | _        y )Nr[   r   encoderpoolerr5   )	rA   rB   rC   r9   r[   r%  rw  r>  rx  )rR   rC   add_pooling_layerrS   rT   s       r7   rB   zTFTapasMainLayer.__init__D  sM    "6"+FF%f9=>OmF:UYr6   c                    | j                   S r   )r[   rW  s    r7   get_input_embeddingsz%TFTapasMainLayer.get_input_embeddingsM  s    r6   c                `    || j                   _        t        |      d   | j                   _        y rZ  )r[   rW   r   r`   r[  s     r7   set_input_embeddingsz%TFTapasMainLayer.set_input_embeddingsP  s$    !&%/%6q%9"r6   c                    t         )z
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
        class PreTrainedModel
        r   )rR   heads_to_prunes     r7   _prune_headszTFTapasMainLayer._prune_headsT  s
    
 "!r6   c                   ||t        d      |t        |      }n|t        |      d d }nt        d      |t        j                  |d      }|8t        j                  |t	        | j
                  j                        gz   d      }| j                  |||||
      }t        j                  ||d   dd|d   f      }t        j                  ||j                        }t        j                  d	|j                        }t        j                  d
|j                        }t        j                  t        j                  ||      |      }|t        d g| j
                  j                  z  }| j!                  |||d d d d |||	|
      }|d   }| j"                  | j#                  |      nd }|	s
||f|dd  z   S t%        |||j&                  |j(                        S )NzDYou cannot specify both input_ids and inputs_embeds at the same timerj   z5You have to specify either input_ids or inputs_embedsr    rk   r   )r   r   r   r   ry   r   r"   r%   )r.   r   r   r   r   r/  r2  r   r3  r4  ry   r  )r.  pooler_outputr.   r/   )r   r   r]   rz   rD   rC   rE   r[   r   r   r   constantr   subtractr   r'  rw  rx  r   r.   r/   )rR   r   r   r   r   r   r   r   r3  r4  ry   rf   embedding_outputextended_attention_maskone_cstten_thousand_cstencoder_outputsro  rD  s                      r7   r   zTFTapasMainLayer.call[  s     ]%>cdd"$Y/K&$]3CR8KTUU!WW+Q?N!WW+T[[=Y=Y9Z8[*[cdeN??%)' + 
 #%**^k!naQRT_`aTb=c"d #%''*AIYI_I_"`++c)9)?)?@;;x7G7M7MN"$++bkk'CZ.[]m"n  %%!>!>>I,,*2"&#' /!5# ' 
 *!,FJkkF]/Bcg  #$ $
 ,-')77&11	
 	
r6   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)NTr[   rw  rx  )	rc   rd   r]   r^   r[   r>   re   rw  rx  r   s     r7   re   zTFTapasMainLayer.build  s   ::
4t,8t334 ,%%d+,4D)5t||001 )""4()44(4t{{//0 (!!$'( ( 5, ,) )( (s$   D%%D1?D=%D.1D:=E)T)rC   r!   ry  r   rh  ri  
NNNNNNNNNF)r   TFModelInputType | Noner   np.ndarray | tf.Tensor | Noner   r  r   r  r   r  r   r  r   r<  r3  r<  r4  r<  ry   r   r   5Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]r   )r0   r1   r2   r!   config_classrB   r{  r}  r  r   r   re   r   r   s   @r7   ru  ru  @  s    LZ:"  .28<8<6:377;,0/3&*[
*[
 6[
 6	[

 4[
 1[
 5[
 *[
 -[
 $[
 [
 
?[
 [
z(r6   ru  c                  (    e Zd ZdZeZdZed        Zy)TFTapasPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    tapasc                    t        j                  dt         j                  d      t        j                  dt         j                  d      t        j                  dt         j                  d      dS )N)NNr   r   r   )NN   r   )r   r   r   )r]   
TensorSpecint32float32rW  s    r7   input_signaturez&TFTapasPreTrainedModel.input_signature  sL     |RXXKP mmL"**K[\ mmORXXL\]
 	
r6   N)	r0   r1   r2   r3   r!   r  base_model_prefixpropertyr  r5   r6   r7   r  r    s&    
 L
 
r6   r  a{	  

    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 ([`TapasConfig`]): 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 (`np.ndarray`, `tf.Tensor`, `List[tf.Tensor]` ``Dict[str, tf.Tensor]` or `Dict[str, np.ndarray]` and each example must have the 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 (`np.ndarray` 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 (`np.ndarray` or `tf.Tensor` of shape `({0}, 7)`, *optional*):
            Token indices that encode tabular structure. Indices can be obtained using [`AutoTokenizer`]. See this
            class for more info.

            [What are token type IDs?](../glossary#token-type-ids)
        position_ids (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. If
            `reset_position_index_per_cell` of [`TapasConfig`] is set to `True`, relative position embeddings will be
            used. Selected in the range `[0, config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        head_mask (`np.ndarray` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        inputs_embeds (`np.ndarray` or `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 bare Tapas 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e	e
      	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     Zd	dZ xZS )
TFTapasModelc                P    t        |   |g|i | t        |d      | _        y )Nr  r   )rA   rB   ru  r  rR   rC   rw   rS   rT   s       r7   rB   zTFTapasModel.__init__?  s(    3&3F3%f7;
r6   batch_size, sequence_lengthoutput_typer  c                <    | j                  |||||||||	|

      }|S )ag  
        Returns:

        Examples:

        ```python
        >>> from transformers import AutoTokenizer, TapasModel
        >>> import pandas as pd

        >>> tokenizer = AutoTokenizer.from_pretrained("google/tapas-base")
        >>> model = TapasModel.from_pretrained("google/tapas-base")

        >>> data = {
        ...     "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"],
        ...     "Age": ["56", "45", "59"],
        ...     "Number of movies": ["87", "53", "69"],
        ... }
        >>> table = pd.DataFrame.from_dict(data)
        >>> queries = ["How many movies has George Clooney played in?", "How old is Brad Pitt?"]

        >>> inputs = tokenizer(table=table, queries=queries, padding="max_length", return_tensors="tf")
        >>> outputs = model(**inputs)

        >>> last_hidden_states = outputs.last_hidden_state
        ```
r   r   r   r   r   r   r   r3  r4  ry   )r  )rR   r   r   r   r   r   r   r   r3  r4  ry   r   s               r7   r   zTFTapasModel.callD  s=    R **))%'/!5#  
 r6   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  )rc   rd   r]   r^   r  r>   re   r   s     r7   re   zTFTapasModel.build|  sg    ::
4$'3tzz/ '

  &' ' 4' 'rr  r   r  )r   r  r   r  r   r  r   r  r   r  r   r  r   r<  r3  r<  r4  r<  ry   r<  r   r  r   )r0   r1   r2   rB   r   r   TAPAS_INPUTS_DOCSTRINGformatr   r   _CONFIG_FOR_DOCr   re   r   r   s   @r7   r  r  :  s    
<
 *+A+H+HIf+gh+GVef .28<8<6:377;,0/3&*#(3*3 63 6	3
 43 13 53 *3 -3 $3 !3 
?3 g i 3j'r6   r  z3Tapas Model with a `language modeling` head on top.c                       e Zd Zd fdZddZe eej                  d             e	e
e      	 	 	 	 	 	 	 	 	 	 	 d		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d
d                     ZddZ xZS )TFTapasForMaskedLMc                    t        |   |g|i | |j                  rt        j	                  d       t        |dd      | _        t        || j                  j                  d      | _	        y )NznIf you want to use `TFTapasForMaskedLM` make sure `config.is_decoder=False` for bi-directional self-attention.Fr  )ry  r>   cls)rP  r>   )
rA   rB   r   loggerwarningru  r  rk  r[   lm_headr  s       r7   rB   zTFTapasForMaskedLM.__init__  sa    3&3F3NN1
 &fGT
%ftzz?T?T[`ar6   c                .    | j                   j                  S r   )r  rm  rW  s    r7   get_lm_headzTFTapasForMaskedLM.get_lm_head  s    ||'''r6   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` or `np.ndarray` 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]`

        Returns:

        Examples:

        ```python
        >>> from transformers import AutoTokenizer, TapasForMaskedLM
        >>> import pandas as pd

        >>> tokenizer = AutoTokenizer.from_pretrained("google/tapas-base")
        >>> model = TapasForMaskedLM.from_pretrained("google/tapas-base")

        >>> data = {
        ...     "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"],
        ...     "Age": ["56", "45", "59"],
        ...     "Number of movies": ["87", "53", "69"],
        ... }
        >>> table = pd.DataFrame.from_dict(data)

        >>> inputs = tokenizer(
        ...     table=table, queries="How many [MASK] has George [MASK] played in?", return_tensors="tf"
        ... )
        >>> labels = tokenizer(
        ...     table=table, queries="How many movies has George Clooney played in?", return_tensors="tf"
        ... )["input_ids"]

        >>> outputs = model(**inputs, labels=labels)
        >>> logits = outputs.logits
        ```r  r   Nlabelsr+   rs   r)   r+   r.   r/   )r  r  hf_compute_lossr   r.   r/   )rR   r   r   r   r   r   r   r   r3  r4  r  ry   r   ro  rp  r)   r   s                    r7   r   zTFTapasForMaskedLM.call  s    f **))%'/!5#  
 "!* LL9~t4+?+?vVg+?+h')GABK7F)-)9TGf$EvE$!//))	
 	
r6   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  )rc   rd   r]   r^   r  r>   re   r  r   s     r7   re   zTFTapasForMaskedLM.build  s    ::
4$'3tzz/ '

  &'4D)5t||001 )""4() ) 6' ') )r   r   rh  NNNNNNNNNNF)r   r  r   r  r   r  r   r  r   r  r   r  r   r<  r3  r<  r4  r<  r  r  ry   r<  r   z)Union[TFMaskedLMOutput, Tuple[tf.Tensor]]r   )r0   r1   r2   rB   r  r   r   r  r  r   r   r  r   re   r   r   s   @r7   r  r    s    
b( *+A+H+HIf+gh+;/Z .28<8<6:377;,0/3&*04#(I
*I
 6I
 6	I

 4I
 1I
 5I
 *I
 -I
 $I
 .I
 !I
 
3I
 [ i I
V	)r6   r  c                  (     e Zd Zd fdZddZ xZS )TFTapasComputeTokenLogitsc           
        t        |   di | |j                  | _        t        j                  d      5  | j                  d|j                  ft        j                  d|j                  rt        j                         n)t        j                  j                  |j                              | _        | j                  dddt        j                               | _        d d d        y # 1 sw Y   y xY w)	Nr   output_weightsTstddevr>   rX   r   rU  rY   output_biasr5   r>   rX   rU  rY   )rA   rB   temperaturer]   r^   r_   rH   r  #init_cell_selection_weights_to_zerozeros_initializerr   initializersTruncatedNormalrJ   r  r  rQ   s      r7   rB   z"TFTapasComputeTokenLogits.__init__  s    "6"!--]]8$ 	"&//%))+jj== 002''77v?W?W7X #2 #D  $"""J^J^J`  /  D	 	 	s   B)C))C2c                |    t        j                  d|| j                        | j                  z   | j                  z  }|S )a  
        Computes logits per token

        Args:
            sequence_output (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
                Also known as last_hidden_state. Sequence of hidden-states at the output of the last layer of the
                model.

        Returns:
            logits (`tf.Tensor` of shape `(batch_size, sequence_length)`): Logits per token.
        	bsj,j->bs)r]   einsumr  r  r  )rR   ro  r+   s      r7   r   zTFTapasComputeTokenLogits.call  s9     ))K$:M:MNQUQaQaaeieueuur6   r   rs  r0   r1   r2   rB   r   r   r   s   @r7   r  r    s    &r6   r  c                  (     e Zd Zd fdZddZ xZS )TFTapasComputeColumnLogitsc           
        t        |   di | t        j                  d      5  | j	                  d|j
                  gt        j                  d|j                  rt        j                         n)t        j                  j                  |j                              | _        | j	                  dddt        j                               | _        d d d        y # 1 sw Y   y xY w)	Ncolumn_outputcolumn_output_weightsTr  r  column_output_biasr5   r  )rA   rB   r]   r^   r_   rH   r  r  r  r   r  r  rJ   r  r  rQ   s      r7   rB   z#TFTapasComputeColumnLogits.__init__  s    "6"]]?+ 	)-,))*jj== 002''77v?W?W7X *9 *D& '+oo)tQSQeQeQg '6 'D#	 	 	s   B)CC!c                b   t        j                  d|| j                        | j                  z   }t	        ||      \  }}|j                  |      }t        ||z  |      \  }	}
t        ||      \  }}|	|t        z   z  }	t        j                  |dk  t        j                  |
j                  d            }|	t        t        j                  |t         j                        z  z  }	|sL|	t        t        j                  t        j                  |
j                  d      t         j                        z  z  }	|	S )aR  
        Computes the column logits.

        Args:
            sequence_output (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
                Also known as last_hidden_state. Sequence of hidden-states at the output of the last layer of the
                model.
            cell_index (`ProductIndexMap`):
                Index that groups tokens into cells.
            cell_mask (`tf.Tensor` of shape `(batch_size, max_num_rows * max_num_cols)`):
                Mask for cells that exist in the table (i.e. that are not padding).
            allow_empty_column_selection (`bool`):
                Whether to allow not to select any column

        Returns:
            column_logits (`tf.Tensor`of shape `(batch_size, max_num_cols)`): Tensor containing the column logits for
            every example in the batch.
        r  g      ?r   )r]   r  r  r  reduce_meanproject_inner
reduce_sumEPSILON_ZERO_DIVISIONlogical_and	not_equalru   CLOSE_ENOUGH_TO_LOG_ZEROr   r  equal)rR   ro  
cell_index	cell_maskallow_empty_column_selectiontoken_logitscell_logitscell_logits_indexcolumn_indexcolumn_logits	out_index
cell_count_
is_paddings                 r7   r   zTFTapasComputeColumnLogits.call&  s
   * yyot?Y?YZ]a]t]tt *5\:)N&& "//0AB#-kI.E|#T y"9l;
A&;;; ^^J$4bll9CTCTVW6XY
1BGGJ

4SSS+5IZIZ\]@^`b`j`j8kkkMr6   r   )r   r*   r  r   s   @r7   r  r    s    "(r6   r  a  
    Tapas Model with a cell selection head and optional aggregation head on top for question-answering tasks on tables
    (linear layers on top of the hidden-states output to compute `logits` and optional `logits_aggregation`), e.g. for
    SQA, WTQ or WikiSQL-supervised tasks.
    c                       e Zd Zd fdZe eej                  d             ee	e
      	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     Zd	dZ xZS )
TFTapasForQuestionAnsweringc                   t        |   |g|i | t        |d      | _        t        j
                  j                  |j                        | _        t        |d      | _
        t        |d      | _        |j                  dkD  rDt        j
                  j                  |j                  t        |j                         d      | _        || _        y )Nr  r   compute_token_logitscompute_column_logitsr   aggregation_classifierr   r>   )rA   rB   ru  r  r   rK   rN   rO   rP   r  r  r  r  num_aggregation_labelsr   r   rJ   r  rC   r  s       r7   rB   z$TFTapasForQuestionAnswering.__init__Z  s    3&3F3 &f7;
 ||++F,F,FG$=fKa$b!%?Md%e"((1,*/,,*<*<--#263K3K#L- += +D'
 r6   r  r  c                   | j                  ||||||||||
      }|d   }|d   }| j                  |      }|t        |      }nt        |      dd }|7t        j                  |t        | j                  j                        gz   d      }g d}|dddd|j                  d      f   }|dddd|j                  d      f   }t        t        j                  t        j                  |t        j                        | j                  j                  dz
        | j                  j                  d	      }t        t        j                  t        j                  |t        j                        | j                  j                  dz
        | j                  j                  d	      }t        ||      }|t        |      nt        |      dd }|t        j                   |      }|@t        j"                  |dkD  t        j$                  |      t        j&                  |            }t        j                  |t        j(                        }t        j                  |t        j(                        }t+        ||      \  }}| j-                  |      }d} | j                  j.                  r(| j1                  |||| j                  j2                        } d}!| j                  j4                  dkD  r| j7                  |      }!t        j8                  d
t        j(                        }"d}#|d}#| j                  j4                  dkD   xs | j                  j:                   }$|$rd}%na|	Rt        |      d   t        |	      d   k(  sJ d       t=        |	|| j                  j>                  || j6                        }%nd}%tA        d      | j                  jB                  rt+        ||      \  }&}tE        |&|      }tF        jH                  jK                  |      }'d}(| j                  j.                  st        j"                  |dk(  t        j$                  |t        j(                        | j                  jL                  t        j$                  |t        j(                        z        })|'jO                  |       |)z  }*t        jP                  |*|z  d      t        jP                  |d      tR        z   z  }(n3tU        || ||||      \  }(}tF        jH                  jK                  |      }'| j                  jV                  rn9|$r|"t        j*                  |(      z  }"n|"t        j*                  |(d|%z
  z        z  }"| j                  j4                  dkD  r|$r~|qt        |      d   t        |      d   k(  sJ d       tY        |!|%|| j                  j:                  | j                  j4                  | j                  jZ                        }+ntA        d      t        j8                  t        |      d   t        j                        }tY        |!|%|| j                  j:                  | j                  j4                  | j                  jZ                        }+| j                  j:                  rR|
E|Ct        |
      t        |      k(  sJ t]        |	|%|'|
|||!| j                        \  },}-|+|,z  }+|+|-z  }+ntA        d      |"t        j*                  |+      z  }"n(t        j&                  |      }tU        || ||||      \  }}|s||!f|dd z   }.|#r|"f|.z   S |.S t_        |#r|"nd||!|j`                  |jb                        S )aF  
        table_mask (`tf.Tensor` of shape `(batch_size, seq_length)`, *optional*):
            Mask for the table. Indicates which tokens belong to the table (1). Question tokens, table headers and
            padding are 0.
        labels (`tf.Tensor` of shape `(batch_size, seq_length)`, *optional*):
            Labels per token for computing the hierarchical cell selection loss. This encodes the positions of the
            answer appearing in the table. Can be obtained using [`AutoTokenizer`].

            - 1 for tokens that are **part of the answer**,
            - 0 for tokens that are **not part of the answer**.

        aggregation_labels (`tf.Tensor` of shape `(batch_size, )`, *optional*):
            Aggregation function index for every example in the batch for computing the aggregation loss. Indices
            should be in `[0, ..., config.num_aggregation_labels - 1]`. Only required in case of strong supervision for
            aggregation (WikiSQL-supervised).
        float_answer (`tf.Tensor` of shape `(batch_size, )`, *optional*):
            Float answer for every example in the batch. Set to *float('nan')* for cell selection questions. Only
            required in case of weak supervision (WTQ) to calculate the aggregate mask and regression loss.
        numeric_values (`tf.Tensor` of shape `(batch_size, seq_length)`, *optional*):
            Numeric values of every token, NaN for tokens which are not numeric values. Can be obtained using
            [`AutoTokenizer`]. Only required in case of weak supervision for aggregation (WTQ) to calculate the
            regression loss.
        numeric_values_scale (`tf.Tensor` of shape `(batch_size, seq_length)`, *optional*):
            Scale of the numeric values of every token. Can be obtained using [`AutoTokenizer`]. Only required in case
            of weak supervision for aggregation (WTQ) to calculate the regression loss.

        Returns:

        Examples:

        ```python
        >>> from transformers import AutoTokenizer, TapasForQuestionAnswering
        >>> import pandas as pd

        >>> tokenizer = AutoTokenizer.from_pretrained("google/tapas-base-finetuned-wtq")
        >>> model = TapasForQuestionAnswering.from_pretrained("google/tapas-base-finetuned-wtq")

        >>> data = {
        ...     "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"],
        ...     "Age": ["56", "45", "59"],
        ...     "Number of movies": ["87", "53", "69"],
        ... }
        >>> table = pd.DataFrame.from_dict(data)
        >>> queries = ["How many movies has George Clooney played in?", "How old is Brad Pitt?"]

        >>> inputs = tokenizer(table=table, queries=queries, padding="max_length", return_tensors="tf")
        >>> outputs = model(**inputs)

        >>> logits = outputs.logits
        >>> logits_aggregation = outputs.logits_aggregation
        ```r  r   r    Nrj   )segment_ids
column_idsrow_idsprev_labelscolumn_ranksinv_column_ranksnumeric_relationsr  r  ru   num_segmentsrr   )r    )rX   r   FTz>Make sure the answers are a FloatTensor of shape (batch_size,)zJYou have to specify float answers in order to calculate the aggregate maskr+   r   rp   r"   zHMake sure the aggregation labels are a LongTensor of shape (batch_size,)zQYou have to specify aggregation labels in order to calculate the aggregation losszeYou have to specify numeric values and numeric values scale in order to calculate the regression lossrs   )r)   r+   r,   r.   r/   )2r  rP   r   r]   rz   rD   rC   rE   indexr~   r   r   r  max_num_rowsmax_num_columnsr   oneswhere	ones_like
zeros_liker  r  r  select_one_columnr  r  r  r  rS  use_answer_as_supervision_calculate_aggregate_maskcell_selection_preferencer   average_logits_per_cellr   tfpdistributions	Bernoullipositive_label_weightlog_probr  r  "_single_column_cell_selection_lossdisable_per_token_loss_calculate_aggregation_lossaggregation_loss_weight_calculate_regression_lossr'   r.   r/   )/rR   r   r   r   r   r   r   
table_maskaggregation_labelsfloat_answernumeric_valuesnumeric_values_scaler   r3  r4  r  ry   r   ro  rD  rf   token_typesr  r  r   r   r  input_mask_floattable_mask_floatr  r  r+   r  r,   
total_losscalculate_lossis_supervisedaggregate_masklogits_per_celldist_per_tokenselection_loss_per_examplerW   selection_loss_per_tokenper_example_additional_lossanswer_losslarge_answer_loss_maskr   s/                                                  r7   r   z TFTapasForQuestionAnswering.callo  s    T **))%'/!5#  
 "!*
,,7 $Y/K$]3CR8K !WW[C8T8T4U3V%VXYZN
 !A{'8'8'C!CD#Aq+*;*;L*I$IJ
 JJrwww94;;;S;SVW;WX11
	
 JJrwwz288<dkk>Y>Y\]>]^44
	
 %Y	:
 09/Dj+*UbJcdgegJh!WW[1N'A+r||G/DbmmT[F\]J77>2::>77:rzz: ##3Z@	1 **?; ;;(( 66Y8`8`M
 ";;--1!%!<!<]!K XXD

;
!N $ B BQ FFsdkkNsNsJsM !%+"6*1-L1I!1LLXWXL &?$%==33&N &*N$%qrr {{22%0%D"< ..888GN *.&;;00aKLLrzz:KK55VSUS]S]8^^
 -;,C,CF,K+Kf+T(-/]];SVf;fmn-oMM"2;>SS.* 6XM6:y)62*F "%!2!2!<!<F!<!K {{11bnn-GHH
 bnn-G3Q_K_-`aa
 {{11A5 )5&v.q1Z@R5STU5VVfefV6Q.*. KKAA KK>> KK??73 )o  *,*V2DQ2Grxx)X&2M*&*==::;;3/ ;;88%16J6V).9ZH\=]]]]>X(***0,. KK	?;%; 4{B337MM3(/  bnn-HII
 ]]6*F:vz9iIAv 01GABK?F/=ZMF*I6I--41!//))
 	
r6   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       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   1xY w# 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  r  )rc   rd   r]   r^   r  r>   re   r  r  r  rC   rH   r   s     r7   re   z!TFTapasForQuestionAnswering.build  sq   ::
4$'3tzz/ '

  &'4/6Bt88==> 6))//5640$7Ct99>>? 7**00674148Dt::??@ Y++114t{{?V?V2WXY Y E' '6 67 7Y Ys0   F%F#?F/3F;F #F,/F8;Gr   )NNNNNNNNNNNNNNNF)"r   r  r   r  r   r  r   r  r   r  r   r  r  r  r  r  r  r  r  r  r  r  r   r<  r3  r<  r4  r<  r  r  ry   r<  r   z7Union[TFTableQuestionAnsweringOutput, Tuple[tf.Tensor]]r   )r0   r1   r2   rB   r   r   r  r  r   r'   r  r   re   r   r   s   @r7   r  r  Q  s>   * *+A+H+HIf+gh+IXgh .28<8<6:377;48<@6:8<>B,0/3&*04#(#b
*b
 6b
 6	b

 4b
 1b
 5b
 2b
 :b
 4b
 6b
 <b
 *b
 -b
 $b
  .!b
" !#b
$ 
A%b
 i i b
H	Yr6   r  z
    Tapas Model with a sequence classification head on top (a linear layer on top of the pooled output), e.g. for table
    entailment tasks, such as TabFact (Chen et al., 2020).
    c                       e Zd Zd fdZe eej                  d             ee	e
      	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     Zd	dZ xZS )
 TFTapasForSequenceClassificationc                h   t        |   |g|i | |j                  | _        t        |d      | _        t
        j                  j                  |j                  d      | _	        t
        j                  j                  |j                  t        |j                        d      | _        || _        y )Nr  r   rP   
classifierr  )rA   rB   
num_labelsru  r  r   rK   rN   rO   rP   r   r   rJ   r%  rC   r  s       r7   rB   z)TFTapasForSequenceClassification.__init__  s    3&3F3 ++%f7;
||++F,F,FY+W,,,,/&BZBZ2[bn - 
 r6   z(batch_size, num_choices, sequence_lengthr  c                *   | j                  |||||||||	|
      }|d   }| j                  ||      }| j                  |      }|
dn| j                  |
|      }|	s|f|dd z   }||f|z   S |S t	        |||j
                  |j                        S )	aw  
        labels (`torch.LongTensor` 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). Note: this is called
            "classification_class_index" in the original implementation.

        Returns:

        Examples:

        ```python
        >>> from transformers import AutoTokenizer, TapasForSequenceClassification
        >>> import tensorflow as tf
        >>> import pandas as pd

        >>> tokenizer = AutoTokenizer.from_pretrained("google/tapas-base-finetuned-tabfact")
        >>> model = TapasForSequenceClassification.from_pretrained("google/tapas-base-finetuned-tabfact")

        >>> data = {
        ...     "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"],
        ...     "Age": ["56", "45", "59"],
        ...     "Number of movies": ["87", "53", "69"],
        ... }
        >>> table = pd.DataFrame.from_dict(data)
        >>> queries = [
        ...     "There is only one actor who is 45 years old",
        ...     "There are 3 actors which played in more than 60 movies",
        ... ]

        >>> inputs = tokenizer(table=table, queries=queries, padding="max_length", return_tensors="tf")
        >>> labels = tf.convert_to_tensor([1, 0])  # 1 means entailed, 0 means refuted

        >>> outputs = model(**inputs, labels=labels)
        >>> loss = outputs.loss
        >>> logits = outputs.logits
        ```r  r    rx   rv   Nr  rs   r  )r  rP   r%  r  r   r.   r/   )rR   r   r   r   r   r   r   r   r3  r4  r  ry   r   rD  r+   r)   r   s                    r7   r   z%TFTapasForSequenceClassification.call  s    n **))%'/!5#  
  
MHM6~t4+?+?vV\+?+]Y,F)-)9TGf$EvE)!//))	
 	
r6   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       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  rP   r%  )rc   rd   r]   r^   r  r>   re   rP   r%  rC   rH   r   s     r7   re   z&TFTapasForSequenceClassification.build  s   ::
4$'3tzz/ '

  &'4D)5t||001 )""4()4t,8t334 M%%tT4;;3J3J&KLM M 9' ') )M Ms$   D<%E?3E<EEEr   r  )r   r  r   r  r   r  r   r  r   r  r   r  r   r<  r3  r<  r4  r<  r  r  ry   r<  r   z3Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]r   )r0   r1   r2   rB   r   r   r  r  r   r   r  r   re   r   r   s   @r7   r#  r#    s    	 *+A+H+HIs+tu+ETcd .28<8<6:377;,0/3&*04#(N
*N
 6N
 6	N

 4N
 1N
 5N
 *N
 -N
 $N
 .N
 !N
 
=N
 e v N
`Mr6   r#  c                      e Zd ZdZdZdZy)AverageApproximationFunctionratiofirst_ordersecond_orderN)r0   r1   r2   RATIOFIRST_ORDERSECOND_ORDERr5   r6   r7   r*  r*     s    EK!Lr6   r*  c                      e Zd ZdZddZd Zy)r~   z'Index grouping entries within a tensor.c                z    t        j                  |      | _        t        j                  |      | _        || _        y)aT  
        Creates an index.

        Args:
          indices: <int32> Tensor of indices, same shape as `values`.
          num_segments: <int32> Scalar tensor, the number of segments. All elements
            in a batched segmented tensor must have the same number of segments (although many segments can be empty).
          batch_dims: Python integer, the number of batch dimensions. The first
            `batch_dims` dimensions of a SegmentedTensor are treated as batch dimensions. Segments in different batch
            elements are always distinct even if they have the same index.
        N)r]   convert_to_tensorru   r  rr   )rR   ru   r  rr   s       r7   rB   zIndexMap.__init__,  s0     ++G400>$r6   c                Z    t        j                  | j                        d | j                   S r   )r]   rX   ru   rr   rW  s    r7   batch_shapezIndexMap.batch_shape<  s!    xx%&788r6   N)r   )r0   r1   r2   r3   rB   r5  r5   r6   r7   r~   r~   )  s    1% 9r6   r~   c                  .     e Zd ZdZ fdZd Zd Z xZS )r   zThe product of two indices.c                p   |j                   |j                   k7  rt        d      t        t        |   |j
                  |j
                  t        j                  |j                  |j
                  j                        z  z   |j                  |j                  z  |j                          || _
        || _        y)a  
        Combines indices i and j into pairs (i, j). The result is an index where each segment (i, j) is the
        intersection of segments i and j. For example if the inputs represent table cells indexed by respectively rows
        and columns the output will be a table indexed by (row, column) pairs, i.e. by cell. The implementation
        combines indices {0, .., n - 1} and {0, .., m - 1} into {0, .., nm - 1}. The output has `num_segments` equal to
        `outer_index.num_segements` * `inner_index.num_segments`.

        Args:
          outer_index: IndexMap.
          inner_index: IndexMap, must have the same shape as `outer_index`.
        zCouter_index.batch_dims and inner_index.batch_dims must be the same.r  N)rr   r   rA   r   rB   ru   r]   r   r  r   outer_indexinner_index)rR   r8  r9  rT   s      r7   rB   zProductIndexMap.__init__C  s     !![%;%;;bccot-##%%0H0H+J]J]JcJc(dde %11K4L4LL"-- 	. 	
 '&r6   c                    t        t        j                  j                  |j                  | j
                  j                        | j                  j                  |j                        S )zDProjects an index with the same index set onto the outer components.r  )	r~   r]   r   floordivru   r9  r  r8  rr   rR   r  s     r7   project_outerzProductIndexMap.project_outer]  K    GG$$U]]D4D4D4Q4QR))66''
 	
r6   c                    t        t        j                  j                  |j                  | j
                  j                        | j
                  j                  |j                        S )zDProjects an index with the same index set onto the inner components.r  )r~   r]   r   floormodru   r9  r  rr   r<  s     r7   r  zProductIndexMap.project_innere  r>  r6   )r0   r1   r2   r3   rB   r=  r  r   r   s   @r7   r   r   @  s    %'4

r6   r   c                \    t        j                  | |j                  |j                  |      S )a  
    Gathers from `values` using the index map. For each element in the domain of the index map this operation looks up
    a value for that index in `values`. Two elements from the same segment always get assigned the same value.

    Args:
      values: [B1, ..., Bn, num_segments, V1, ...] Tensor with segment values.
      index: [B1, ..., Bn, I1, ..., Ik] IndexMap.
      name: Name for the TensorFlow operation.

    Returns:
      [B1, ..., Bn, I1, ..., Ik, V1, ...] Tensor with the gathered values.
    )rr   r>   )r]   r   ru   rr   valuesr  r>   s      r7   r   r   n  s#     99VU]]u7G7GdSSr6   c                @   t        j                  | j                               }t        j                  |      | j                  z  }t        j
                  || j                               }t        | j                  | j                  j                  j                        D ]  }t        j                  |d      } t        j                  || j                  j                        | j                  z   }t        t        j
                  |dg      | j                  |z  d      S )a  
    Flattens a batched index map to a 1d index map. This operation relabels the segments to keep batch elements
    distinct. The k-th batch element will have indices shifted by `num_segments` * (k - 1). The result is a tensor with
    `num_segments` multiplied by the number of elements in the batch.

    Args:
      index: IndexMap to flatten.
      name: Name for the TensorFlow operation.

    Returns:
      The flattened IndexMap.
    rj   r   r  )r]   reduce_prodr5  r|   r  r   rr   ru   rX   rankr{   r   r   r~   )r  r>   r   offsetr  ru   s         r7   flattenrH  ~  s      1 1 34JXXj!E$6$66FZZ 1 1 34F5##U]]%8%8%=%=> ,+, ggfemm112U]]BGBJJw5EDVDVYcDcpqrrr6   c                l   t        j                  |       } | j                  j                  d       t        j                  |      }|j                  j                  d       t        j                  |      }t        j
                  t        j                  | t         j                        t        j                  |d      gd      }t        j                  ||      }t        j
                  | dggd      }t        j                  ||      }t        ||| j                  j                         d         S )a  
    Constructs an index map equal to range(num_segments).

    Args:
        batch_shape (`tf.Tensor`):
            Batch shape
        num_segments (`int`):
            Number of segments
        name (`str`, *optional*, defaults to 'range_index_map'):
            Name for the operation. Currently not used

    Returns:
        (`IndexMap`): IndexMap of shape batch_shape with elements equal to range(num_segments).
    r    r   r   rp   r  )r]   r3  rX   assert_has_rankr|   r   r  r  r{   r   tiler~   as_list)r5  r  r>   ru   rX   	multipless         r7   range_index_maprN    s     &&{3K%%a(''5L&&q)hh|$GIIr||Krxx@"..Q]deBfgnopEjj%(G		;,15Igggy)GG,;K\K\KdKdKfghKijjr6   c                   t        |      }t        j                  |       |j                  j                  j                  d }t        j
                  dg|gd      }t        j                  | |      } |||j                  |j                        }t        j
                  |j                         |j                  g|gd      }	t        j                  ||	      }
t        |j                         |j                        }|
|fS )a  
    Applies a segment reduction segment-wise.

    Args:
        values (`tf.Tensor`):
            Tensor with segment values.
        index (`IndexMap`):
            IndexMap.
        segment_reduce_fn (`str`):
            Name for the reduce operation. One of "sum", "mean", "max" or "min".
        name (`str`):
            Name for the operation. Currently not used

    Returns:
        (`IndexMap`): IndexMap of shape batch_shape with elements equal to range(num_segments).
    Nrj   r   rp   )datar  r  )
rH  r]   rX   ru   rF  r   r   r  r5  rN  )rC  r  segment_reduce_fnr>   
flat_indexvector_shapeflattened_shapeflat_valuessegment_means	new_shapeoutput_valuesoutput_indexs               r7   _segment_reducerZ    s    ( J88F#EMM$7$7$<$<$>?Lii"| 41=O**V_5K%j&8&8zG^G^M
 		5,,.1C1C0DlSZ[\IJJ}i8M"5#4#4#68J8JKL,&&r6   c                N    t        | |t        j                  j                  |      S )a  
    Averages a tensor over its segments. Outputs 0 for empty segments. This operations computes the mean over segments,
    with support for:

      - Batching using the first dimensions [B1, B2, ..., Bn]. Each element in a batch can have different indices.
      - Vectorization using the last dimension [V1, V2, ...]. If they are present the output will be a mean of vectors
        rather than scalars.
    Only the middle dimensions [I1, ..., Ik] are reduced by the operation.

    Args:
      values: [B1, B2, ..., Bn, I1, .., Ik, V1, V2, ..] tensor of values to be
        averaged.
      index: IndexMap [B1, B2, ..., Bn, I1, .., Ik] index defining the segments.
      name: Name for the TensorFlow ops.

    Returns:
      A pair (output_values, output_index) where `output_values` is a tensor of shape [B1, B2, ..., Bn, num_segments,
      V1, V2, ..] and `index` is an IndexMap with shape [B1, B2, ..., Bn, num_segments].
    )rZ  r]   r   unsorted_segment_meanrB  s      r7   r  r    s    ( 65"''*G*GNNr6   c                N    t        | |t        j                  j                  |      S )a  
    Sums a tensor over its segments. Outputs 0 for empty segments. This operations computes the sum over segments, with
    support for:

      - Batching using the first dimensions [B1, B2, ..., Bn]. Each element in a batch can have different indices.
      - Vectorization using the last dimension [V1, V2, ...]. If they are present the output will be a sum of vectors
        rather than scalars.
    Only the middle dimensions [I1, ..., Ik] are reduced by the operation.

    Args:
      values: [B1, B2, ..., Bn, I1, .., Ik, V1, V2, ..] tensor of values to be
        averaged.
      index: IndexMap [B1, B2, ..., Bn, I1, .., Ik] index defining the segments.
      name: Name for the TensorFlow ops.

    Returns:
      A pair (output_values, output_index) where `output_values` is a tensor of shape [B1, B2, ..., Bn, num_segments,
      V1, V2, ..] and `index` is an IndexMap with shape [B1, B2, ..., Bn, num_segments].
    )rZ  r]   r   unsorted_segment_sumrB  s      r7   r  r    s    ( 65"''*F*FMMr6   c                N    t        | |t        j                  j                  |      S )a  
    Computes the maximum over segments. This operations computes the maximum over segments, with support for:

      - Batching using the first dimensions [B1, B2, ..., Bn]. Each element in a batch can have different indices.
      - Vectorization using the last dimension [V1, V2, ...]. If they are present the output will be an element-wise
        maximum of vectors rather than scalars.
    Only the middle dimensions [I1, ..., Ik] are reduced by the operation.

    Args:
      values: [B1, B2, ..., Bn, I1, .., Ik, V1, V2, ..] tensor of values to be
        averaged.
      index: IndexMap [B1, B2, ..., Bn, I1, .., Ik] index defining the segments.
      name: Name for the TensorFlow ops.

    Returns:
      A pair (output_values, output_index) where `output_values` is a tensor of shape [B1, B2, ..., Bn, num_segments,
      V1, V2, ..] and `index` is an IndexMap with shape [B1, B2, ..., Bn, num_segments].
    )rZ  r]   r   unsorted_segment_maxrB  s      r7   
reduce_maxra    s    & 65"''*F*FMMr6   c                N    t        | |t        j                  j                  |      S )z#Computes the minimum over segments.)rZ  r]   r   unsorted_segment_minrB  s      r7   r   r     s    65"''*F*FMMr6   c           	        t        t        j                  |t        j                        |      \  }}t        j                  |dt        j
                        }t        j                  t        j                  |d      d      }	t        j                  |	t        j                  |      |      }t        j                  j                  |      }
|
j                  |       }t        | |      \  }}t        t        j                  |t        j
                        |      \  }}|j                  |      j                   }t        j                  t        j                  |t        j"                  |d            t        j                        }t        j                  j%                  |      }|j                  |      }t        j                   ||z  |z  d       }|t        j                   ||z  d      t&        z   z  }|}|t        j                  |	t        j                  |      |      z  }t        j                  |dt        j
                        }t        j                  t        j                  |t        j"                  |d            t        j                        }t        j                  t        j                  |d      t        j                  |      |      }|t(        d||z  z
  z  z  }t+        ||      }||fS )a{  
    Computes the loss for cell selection constrained to a single column. The loss is a hierarchical log-likelihood. The
    model first predicts a column and then selects cells within that column (conditioned on the column). Cells outside
    the selected column are never selected.

    Args:
        token_logits (`tf.Tensor` of shape `(batch_size, sequence_length)`):
            Tensor containing the logits per token.
        column_logits (`tf.Tensor` of shape `(batch_size, max_num_cols)`):
            Tensor containing the logits per column.
        labels (`tf.Tensor` of shape `(batch_size, sequence_length)`):
            Labels per token.
        cell_index (`ProductIndexMap`):
            Index that groups tokens into cells.
        col_index (`IndexMap`):
            Index that groups tokens into columns.
        cell_mask (`tf.Tensor` of shape `(batch_size, max_num_rows * max_num_cols)`):
            Mask for cells that exist in the table (i.e. that are not padding).

    Returns:
        selection_loss_per_example (`tf.Tensor` of shape `(batch_size,)`): Loss for each example. logits (`tf.Tensor`
        of shape `(batch_size, sequence_length)`): New logits which are only allowed to select cells in a single
        column. Logits outside of the most likely column according to *column_logits* will be set to a very low value
        (such that the probabilities are 0).
    rj   )rq   r  rp   r   r  r    r"   )r  r]   r   r  argmaxr  r  ra  r  r  r  r  Categoricalr  r  r  ru   r{   r  r  r  r   )r  r  r  r  r   r  labels_per_columnr  column_labelno_cell_selectedcolumn_distcolumn_loss_per_exampler  labels_per_celllabels_indexcolumn_id_for_cellscolumn_mask	cell_distcell_log_prob	cell_lossr  selected_column_idselected_column_maskr+   s                           r7   r	  r	    s`   8 &bggfbjj&A9Mq99.RRXXNL xx.?b I1M88,bmmL.I<XL##//}/EK*33LAA %\:>OQ$.rwwvrxx/H*$U!O\ %22<@HH''"((#6|Z[8\]_a_i_ijK !!++?+CI&&7M}{:YFQOOI{Y6Q?BWWWI!8"((+;R]]Ke=fhq"rr
 =rrxxP77
$bnn5Gb&QRTVT^T^ 88
$a("--8L*MOc /3EY9Y3YZZOOZ0F%v--r6   c                ^   t        j                  t        j                  t         j                  j	                  |             t         j
                        } ||      }t        j                  j                  |      }t        j                  |j                         ddddf   d      }||k  }	t        j                  |d      dkD  }
t        j                  t        j                  |	|
      t        j                  |t         j
                        |      }t        j                  |      }|S )a  
    Finds examples where the model should select cells with no aggregation.

    Returns a mask that determines for which examples should the model select answers directly from the table, without
    any aggregation function. If the answer is a piece of text the case is unambiguous as aggregation functions only
    apply to numbers. If the answer is a number but does not appear in the table then we must use some aggregation
    case. The ambiguous case is when the answer is a number that also appears in the table. In this case we use the
    aggregation function probabilities predicted by the model to decide whether to select or aggregate. The threshold
    for this is a hyperparameter *cell_selection_preference*

    Args:
        answer (`tf.Tensor` of shape `(batch_size, )`):
            Answer for every example in the batch. Nan if there is no scalar answer.
        pooled_output (`tf.Tensor` of shape `(batch_size, hidden_size)`):
            Output of the pooler (BertPooler) on top of the encoder layer.
        cell_selection_preference (`float`):
            Preference for cell selection in ambiguous cases.
        labels (`tf.Tensor` of shape `(batch_size, sequence_length)`):
            Labels per token. aggregation_classifier (`torch.nn.Linear`): Aggregation head

    Returns:
        aggregate_mask (`tf.Tensor` of shape `(batch_size,)`): A mask set to 1 for examples that should use aggregation
        functions.
    r  Nr    rp   r   r   )r]   r   logical_notr   is_nanr  r  r  rf  r  probs_parameterr  r  r  stop_gradient)answerrD  r  r  r  aggregate_mask_initr,   dist_aggregationaggregation_ops_total_massis_pred_cell_selectionis_cell_supervision_availabler  s               r7   r  r  f  s    4 ''"..1G"H"**U/>((44<N4O!#/?/O/O/QRSUVUWRW/X_`!a7;TT$&MM&q$AA$E!XX
-/LM
)<N
 %%n5Nr6   c                2   |r&t        j                  |t         j                        }n|}t        j                  ||t         j                        }t         j
                  j                  | d      }t        j                  ||z  d       }|r|d|z
  z  S |S )a   
    Calculates aggregation loss when its type is known during training.

    In the weakly supervised setting, the only known information is that for cell selection examples, "no aggregation"
    should be predicted. For other examples (those that require aggregation), no loss is accumulated. In the setting
    where aggregation type is always known, standard cross entropy loss is accumulated for all examples

    Args:
        logits_aggregation (`tf.Tensor` of shape `(batch_size, num_aggregation_labels)`):
            Logits per aggregation operation.
        aggregate_mask (`tf.Tensor` of shape `(batch_size, )`):
            A mask set to 1 for examples that should use aggregation functions.
        aggregation_labels (`tf.Tensor` of shape `(batch_size, )`):
            Aggregation function id for every example in the batch.
        use_answer_as_supervision (`bool`, *optional*):
            Whether to use the answer as the only supervision for aggregation examples.
        num_aggregation_labels (`int`, *optional*, defaults to 0):
            The number of aggregation operators to predict.

    Returns:
        aggregation_loss_known (`tf.Tensor` of shape `(batch_size,)`): Aggregation loss (when its type is known during
        training) per example.
    r   )depthr   rj   rp   r    )r]   r  r  one_hotr  rd  log_softmaxr  )	r,   r  r  r   r  target_aggregationone_hot_labels	log_probs$per_example_aggregation_intermediates	            r7   !_calculate_aggregation_loss_knownr    s    4 !]]>J 0ZZ 2:PXZXbXbcN!!"42!>I -/MM.9:T[],^+^(  4q>7IJJ33r6   c                    t         j                  j                  |       }t        j                  |j                         ddddf   d      }t        j                  j                  |       |z  S )a  
    Calculates aggregation loss in the case of answer supervision.

    Args:
        logits_aggregation (`tf.Tensor` of shape `(batch_size, num_aggregation_labels)`):
            Logits per aggregation operation.
        aggregate_mask (`tf.Tensor` of shape `(batch_size, )`):
            A mask set to 1 for examples that should use aggregation functions

    Returns:
        aggregation_loss_unknown (`tf.Tensor` of shape `(batch_size,)`): Aggregation loss (in case of answer
        supervision) per example.
    r  Nr    rp   )r  r  rf  r]   r  rx  r   log)r,   r  r|  r}  s       r7   #_calculate_aggregation_loss_unknownr    sh     ((44<N4O!#/?/O/O/QRSUVUWRW/X_`!a
 GGKK233nDDr6   c                L    t        | ||||      }|r|t        | |      z  }||z  S )a  
    Calculates the aggregation loss per example.

    Args:
        logits_aggregation (`tf.Tensor` of shape `(batch_size, num_aggregation_labels)`):
            Logits per aggregation operation.
        aggregate_mask (`tf.Tensor` of shape `(batch_size, )`):
            A mask set to 1 for examples that should use aggregation functions.
        aggregation_labels (`tf.Tensor` of shape `(batch_size, )`):
            Aggregation function id for every example in the batch.
        use_answer_as_supervision (`bool`, *optional*):
            Whether to use the answer as the only supervision for aggregation examples.
        num_aggregation_labels (`int`, *optional*, defaults to 0):
            The number of aggregation operators to predict.
        aggregation_loss_weight (`float`, *optional*, defaults to 1.0):
            Importance weight for the aggregation loss.

    Returns:
        aggregation_loss (`tf.Tensor` of shape `(batch_size,)`): Aggregation loss per example.
    )r  r  )r,   r  r  r   r  r  per_example_aggregation_losss          r7   r  r    sD    8 $EN,>@Y[q$  !$(KL^`n(oo$"%AAAr6   c                   |j                   rWt        j                  j                  |j                  | j                         |j                  z        }|j                         }n| j                         }||z  |z  }t        j                  |d      }t        j                  t        j                  j                  |      t        j                  |      |      }	t        j                  ||	z  d      }
|j                  }|t        j                   k(  r|
|t"        z   z  }n|t        j$                  k(  r<t        j                  |dd      |z
  dz   }t        j                  |	|z  |z  d      }n|t        j&                  k(  rt        j                  |dd      |z
  dz   }|d|z
  z  }t        j                  |dd      |z
  }|t        j                  j)                  |      z  dz   |z  }t        j                  |	|z  |z  d      }nt+        d|j                        |j,                  rEt        j                  j/                  |j0                  |ddddf         }|j                         }n#t3        |ddddf   |j0                  z  d      }t        j4                  t        j6                  |
d      t        j6                  |d      t        j6                  |d      gd      }t        j                  ||z  d      }|S )	a  
    Calculates the expected result given cell and aggregation probabilities.

    Args:
        dist_per_cell (`tfp.distributions.Bernoulli`):
            Cell selection distribution for each cell.
        numeric_values (`tf.Tensor` of shape `(batch_size, seq_length)`):
            Numeric values of every token. Nan for tokens which are not numeric values.
        numeric_values_scale (`tf.Tensor` of shape `(batch_size, seq_length)`):
            Scale of the numeric values of every token.
        input_mask_float (`tf.Tensor` of shape `(batch_size, seq_length)`):
            Mask for the table, without question tokens and table headers.
        logits_aggregation (`tf.Tensor` of shape `(batch_size, num_aggregation_labels)`):
            Logits per aggregation operation.
        config ([`TapasConfig`]):
            Model configuration class with all the hyperparameters of the model

    Returns:
        expected_result (`tf.Tensor` of shape `(batch_size,)`): The expected result per example.
    r  r    rp   T)rq   keepdimsz*Invalid average_approximation_function: %sNrj   )use_gumbel_for_cellsr  r  RelaxedBernoullir  logits_parametersamplerx  r]   r  r  r   rw  r  average_approximation_functionr*  r.  r  r/  r0  squarer   use_gumbel_for_aggregationRelaxedOneHotCategoricalaggregation_temperaturer   r   r{   )dist_per_cellr  r  r  r,   rC   gumbel_distscaled_probability_per_cellcount_resultnumeric_values_masked
sum_resultavg_approximationaverage_resultexpointwise_varvar
multiplieraggregation_op_only_probsall_resultsexpected_results                       r7   _calculate_expected_resultr    s   . ""''88  113f6H6HH	 9 
 '2&8&8&:#&3&C&C&E# $?AU#UYi"i==!<1ELHH
~&n(E~ :=RRYZ[J==8>>>#|6K'KL	:FF	F]]6QNQllopp'<?Z'Z]_'_fgh	:GG	G]]6QNQllopp3q;V7VWmmMDAMQBGGNN2..2b8
'<?Z'Z]g'gnopEvGlGlmm((''@@**3Eae3L A 
 %0$6$6$8! %33Eae3LvOmOm3mtv$w!))NN:A.NN>2NN<a0	

 K mmK2K$KRSTOr6   c                D   t        ||||||      }t        j                  t        j                  j	                  |       t        j
                  |       |       }	|j                  r t        j                  t        j                  j                  t        j                  j                  |      t        j                  j                  |	            t        z         }
|	|
z  }||
z  }t        j                  j                  j                  j                  ||z  ||z  t        j                  dt        j                         t        j                  j"                  j$                        }nt        j                  j                  j                  j                  |	|z  ||z  t        j                  |j&                  t        j                         t        j                  j"                  j$                        }|j(                  &t        j*                  |t        j                         }njt        j                  ||j(                  kD  t        j
                  |t        j                         t        j*                  |t        j                               }|j,                  ||z  z  }||fS )a  
    Calculates the regression loss per example.

    Args:
        answer (`tf.Tensor` of shape `(batch_size,)`):
            Answer for every example in the batch. Nan if there is no scalar answer.
        aggregate_mask (`tf.Tensor` of shape `(batch_size,)`):
            A mask set to 1 for examples that should use aggregation functions.
        dist_per_cell (`torch.distributions.Bernoulli`):
            Cell selection distribution for each cell.
        numeric_values (`tf.Tensor` of shape `(batch_size, seq_length)`):
            Numeric values of every token. Nan for tokens which are not numeric values.
        numeric_values_scale (`tf.Tensor` of shape `(batch_size, seq_length)`):
            Scale of the numeric values of every token.
        input_mask_float (`tf.Tensor` of shape `(batch_size, seq_length)`):
            Mask for the table, without question tokens and table headers.
        logits_aggregation (`tf.Tensor` of shape `(batch_size, num_aggregation_labels)`):
            Logits per aggregation operation.
        config ([`TapasConfig`]):
            Model configuration class with all the parameters of the model

    Returns:
        per_example_answer_loss_scaled (`tf.Tensor` of shape `(batch_size,)`): Scales answer loss for each example in
        the batch. large_answer_loss_mask (`tf.Tensor` of shape `(batch_size,)`): A mask which is 1 for examples for
        which their answer loss is larger than the answer_loss_cutoff.
    r"   )delta	reductionr   )r  r]   r  r   rw  r  use_normalized_answer_lossry  maximumabsr  compatv1losses
huber_lossr   r  	ReductionNONEhuber_loss_deltaanswer_loss_cutoffr  answer_loss_importance)rz  r  r  r  r  r  r,   rC   r  answer_masked
normalizernormalized_answer_maskednormalized_expected_resultper_example_answer_lossr   per_example_answer_loss_scaleds                   r7   r  r  M	  s   J 1~';=MOaciO
 HHRWW^^F3R]]65JFSM((%%GGOOBGGKK8"''++m:TUXmm

 $1:#= %4z%A""$)),,"5"5"@"@$~5&7''#rzz*ii))..	 #A #
 #%)),,"5"5"@"@N*n,''&112::>ii))..	 #A #
   (!#.ERZZ!X!##f&?&??MM1DLL0

C"

 &,%B%BF]`nFn%o")+AAAr6   )segmented_gather)segmented_flatten)rN  )segmented_reduce_mean)segmented_reduce_sum)segmented_reduce_max)segmented_reduce_min)ir3   
__future__r   enumr   dataclassesr   typingr   r   r   r   numpynp
tensorflowr]   activations_tfr
   modeling_tf_outputsr   r   r   r   modeling_tf_utilsr   r   r   r   r   r   r   r   tf_utilsr   r   r   utilsr   r   r   r   r   r   configuration_tapasr!   
get_loggerr0   r  tensorflow_probabilityr  r  NormalnImportErrorerrorr  r  _CHECKPOINT_FOR_DOCr  r  r'   rK   Layerr9   r   r   r   r   r  r  r%  r>  rG  rM  rk  ru  r  TAPAS_START_DOCSTRINGr  r  r  r  r  r  r#  r   Enumr*  r~   r   r   rH  rN  rZ  r  r  ra  r   r	  r  r  r  r  r  r  r5   r6   r7   <module>r     s    "   ! / /   / 	 	 	 S R  - 
		H	% '(
, $$C$8, $$C$8  )   #  /[ / /:o ** o fAH5<<-- AHJL** L>0.u||)) 0.hH%,,,, H<LELL&& L>d05<<%% d0PK&U\\'' K&^HELL&& H<"LU\\%7%7 "LL-ell00 -b-U\\'' -( D(u||)) D( D(N
. 
$( T3 l eD') D'	D'N OQfgg)/1M g) hg)T! 2 2 !H:!3!3 :z 
 LY"8 LYLY^
  kM'=?[ kMkM\ "3		 "9 9.+
h +
\T s.k8 'FO.N.N,N
F.R)X+4\E0#BLL^HBWH  
u	

  s$   !N .!N( N%$N%(N10N1