modeling_tf_tapas.py 110 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453
  1. # coding=utf-8
  2. # Copyright 2021 Google Research and The HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """TF 2.0 TAPAS model."""
  16. from __future__ import annotations
  17. import enum
  18. import math
  19. from dataclasses import dataclass
  20. from typing import Dict, Optional, Tuple, Union
  21. import numpy as np
  22. import tensorflow as tf
  23. from ...activations_tf import get_tf_activation
  24. from ...modeling_tf_outputs import (
  25. TFBaseModelOutputWithPastAndCrossAttentions,
  26. TFBaseModelOutputWithPooling,
  27. TFMaskedLMOutput,
  28. TFSequenceClassifierOutput,
  29. )
  30. from ...modeling_tf_utils import (
  31. TFMaskedLanguageModelingLoss,
  32. TFModelInputType,
  33. TFPreTrainedModel,
  34. TFSequenceClassificationLoss,
  35. get_initializer,
  36. keras,
  37. keras_serializable,
  38. unpack_inputs,
  39. )
  40. from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
  41. from ...utils import (
  42. ModelOutput,
  43. add_start_docstrings,
  44. add_start_docstrings_to_model_forward,
  45. is_tensorflow_probability_available,
  46. logging,
  47. replace_return_docstrings,
  48. )
  49. from .configuration_tapas import TapasConfig
  50. logger = logging.get_logger(__name__)
  51. # soft dependency
  52. if is_tensorflow_probability_available():
  53. try:
  54. import tensorflow_probability as tfp
  55. # On the first call, check whether a compatible version of TensorFlow is installed
  56. # TensorFlow Probability depends on a recent stable release of TensorFlow
  57. n = tfp.distributions.Normal(loc=0.0, scale=1.0)
  58. except ImportError:
  59. logger.error(
  60. "TAPAS models are not usable since `tensorflow_probability` can't be loaded. "
  61. "It seems you have `tensorflow_probability` installed with the wrong tensorflow version. "
  62. "Please try to reinstall it following the instructions here: https://github.com/tensorflow/probability."
  63. )
  64. else:
  65. try:
  66. import tensorflow_probability as tfp
  67. # On the first call, check whether a compatible version of TensorFlow is installed
  68. # TensorFlow Probability depends on a recent stable release of TensorFlow
  69. _ = tfp.distributions.Normal(loc=0.0, scale=1.0)
  70. except ImportError:
  71. pass
  72. _CONFIG_FOR_DOC = "TapasConfig"
  73. _CHECKPOINT_FOR_DOC = "google/tapas-base"
  74. EPSILON_ZERO_DIVISION = 1e-10
  75. CLOSE_ENOUGH_TO_LOG_ZERO = -10000.0
  76. @dataclass
  77. class TFTableQuestionAnsweringOutput(ModelOutput):
  78. """
  79. Output type of [`TFTapasForQuestionAnswering`].
  80. Args:
  81. loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` (and possibly `answer`, `aggregation_labels`, `numeric_values` and `numeric_values_scale` are provided)):
  82. Total loss as the sum of the hierarchical cell selection log-likelihood loss and (optionally) the
  83. semi-supervised regression loss and (optionally) supervised loss for aggregations.
  84. logits (`tf.Tensor` of shape `(batch_size, sequence_length)`):
  85. Prediction scores of the cell selection head, for every token.
  86. logits_aggregation (`tf.Tensor`, *optional*, of shape `(batch_size, num_aggregation_labels)`):
  87. Prediction scores of the aggregation head, for every aggregation operator.
  88. hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  89. Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
  90. `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus
  91. the initial embedding outputs.
  92. attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  93. Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  94. sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
  95. the self-attention heads.
  96. """
  97. loss: tf.Tensor | None = None
  98. logits: tf.Tensor = None
  99. logits_aggregation: tf.Tensor | None = None
  100. hidden_states: Tuple[tf.Tensor] | None = None
  101. attentions: Tuple[tf.Tensor] | None = None
  102. class TFTapasEmbeddings(keras.layers.Layer):
  103. """
  104. Construct the embeddings from word, position and token_type embeddings. Same as BertEmbeddings but with a number of
  105. additional token type embeddings to encode tabular structure.
  106. """
  107. def __init__(self, config: TapasConfig, **kwargs):
  108. super().__init__(**kwargs)
  109. self.config = config
  110. self.number_of_token_type_embeddings = len(config.type_vocab_sizes)
  111. self.reset_position_index_per_cell = config.reset_position_index_per_cell
  112. self.hidden_size = config.hidden_size
  113. self.max_position_embeddings = config.max_position_embeddings
  114. self.initializer_range = config.initializer_range
  115. self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
  116. self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
  117. def build(self, input_shape=None):
  118. with tf.name_scope("word_embeddings"):
  119. self.weight = self.add_weight(
  120. name="weight",
  121. shape=[self.config.vocab_size, self.hidden_size],
  122. initializer=get_initializer(self.initializer_range),
  123. )
  124. with tf.name_scope("position_embeddings"):
  125. self.position_embeddings = self.add_weight(
  126. name="embeddings",
  127. shape=[self.max_position_embeddings, self.hidden_size],
  128. initializer=get_initializer(self.initializer_range),
  129. )
  130. for i, type_vocab_size in enumerate(self.config.type_vocab_sizes):
  131. with tf.name_scope(f"token_type_embeddings_{i}"):
  132. setattr(
  133. self,
  134. f"token_type_embeddings_{i}",
  135. self.add_weight(
  136. name="embeddings",
  137. shape=[type_vocab_size, self.hidden_size],
  138. initializer=get_initializer(self.initializer_range),
  139. ),
  140. )
  141. if self.built:
  142. return
  143. self.built = True
  144. if getattr(self, "LayerNorm", None) is not None:
  145. with tf.name_scope(self.LayerNorm.name):
  146. self.LayerNorm.build([None, None, self.config.hidden_size])
  147. def call(
  148. self,
  149. input_ids: tf.Tensor = None,
  150. position_ids: tf.Tensor = None,
  151. token_type_ids: tf.Tensor = None,
  152. inputs_embeds: tf.Tensor = None,
  153. training: bool = False,
  154. ) -> tf.Tensor:
  155. """
  156. Applies embedding based on inputs tensor.
  157. Returns:
  158. final_embeddings (`tf.Tensor`): output embedding tensor.
  159. """
  160. assert not (input_ids is None and inputs_embeds is None)
  161. if input_ids is not None:
  162. input_shape = shape_list(input_ids)
  163. else:
  164. input_shape = shape_list(inputs_embeds)[:-1]
  165. seq_length = input_shape[1]
  166. if token_type_ids is None:
  167. token_type_ids = tf.fill(dims=input_shape + [self.number_of_token_type_embeddings], value=0)
  168. if position_ids is None:
  169. # create absolute position embeddings
  170. position_ids = tf.expand_dims(tf.range(start=0, limit=seq_length), axis=0)
  171. position_ids = tf.broadcast_to(position_ids, shape=input_shape)
  172. # when self.config.reset_position_index_per_cell is set to True, create relative position embeddings
  173. if self.reset_position_index_per_cell:
  174. # shape (batch_size, seq_len)
  175. col_index = IndexMap(token_type_ids[:, :, 1], self.config.type_vocab_sizes[1], batch_dims=1)
  176. # shape (batch_size, seq_len)
  177. row_index = IndexMap(token_type_ids[:, :, 2], self.config.type_vocab_sizes[2], batch_dims=1)
  178. # shape (batch_size, seq_len)
  179. full_index = ProductIndexMap(col_index, row_index)
  180. # shape (max_rows * max_columns,). First absolute position for every cell
  181. first_position_per_segment = reduce_min(position_ids, full_index)[0]
  182. # ? shape (batch_size, seq_len). First absolute position of the cell for every token
  183. first_position = gather(first_position_per_segment, full_index)
  184. # shape (1, seq_len)
  185. position = tf.expand_dims(tf.range(start=0, limit=seq_length), axis=0)
  186. position_ids = tf.math.minimum(self.max_position_embeddings - 1, position - first_position)
  187. if input_ids is not None:
  188. check_embeddings_within_bounds(input_ids, self.config.vocab_size)
  189. inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
  190. position_embeddings = tf.gather(self.position_embeddings, indices=position_ids)
  191. final_embeddings = inputs_embeds + position_embeddings
  192. for i in range(self.number_of_token_type_embeddings):
  193. name = f"token_type_embeddings_{i}"
  194. final_embeddings += tf.gather(params=getattr(self, name), indices=token_type_ids[:, :, i])
  195. final_embeddings = self.LayerNorm(inputs=final_embeddings)
  196. final_embeddings = self.dropout(inputs=final_embeddings, training=training)
  197. return final_embeddings
  198. # Copied from transformers.models.bert.modeling_tf_bert.TFBertSelfAttention with Bert->Tapas
  199. class TFTapasSelfAttention(keras.layers.Layer):
  200. def __init__(self, config: TapasConfig, **kwargs):
  201. super().__init__(**kwargs)
  202. if config.hidden_size % config.num_attention_heads != 0:
  203. raise ValueError(
  204. f"The hidden size ({config.hidden_size}) is not a multiple of the number "
  205. f"of attention heads ({config.num_attention_heads})"
  206. )
  207. self.num_attention_heads = config.num_attention_heads
  208. self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
  209. self.all_head_size = self.num_attention_heads * self.attention_head_size
  210. self.sqrt_att_head_size = math.sqrt(self.attention_head_size)
  211. self.query = keras.layers.Dense(
  212. units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="query"
  213. )
  214. self.key = keras.layers.Dense(
  215. units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="key"
  216. )
  217. self.value = keras.layers.Dense(
  218. units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="value"
  219. )
  220. self.dropout = keras.layers.Dropout(rate=config.attention_probs_dropout_prob)
  221. self.is_decoder = config.is_decoder
  222. self.config = config
  223. def transpose_for_scores(self, tensor: tf.Tensor, batch_size: int) -> tf.Tensor:
  224. # Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]
  225. tensor = tf.reshape(tensor=tensor, shape=(batch_size, -1, self.num_attention_heads, self.attention_head_size))
  226. # Transpose the tensor from [batch_size, seq_length, num_attention_heads, attention_head_size] to [batch_size, num_attention_heads, seq_length, attention_head_size]
  227. return tf.transpose(tensor, perm=[0, 2, 1, 3])
  228. def call(
  229. self,
  230. hidden_states: tf.Tensor,
  231. attention_mask: tf.Tensor,
  232. head_mask: tf.Tensor,
  233. encoder_hidden_states: tf.Tensor,
  234. encoder_attention_mask: tf.Tensor,
  235. past_key_value: Tuple[tf.Tensor],
  236. output_attentions: bool,
  237. training: bool = False,
  238. ) -> Tuple[tf.Tensor]:
  239. batch_size = shape_list(hidden_states)[0]
  240. mixed_query_layer = self.query(inputs=hidden_states)
  241. # If this is instantiated as a cross-attention module, the keys
  242. # and values come from an encoder; the attention mask needs to be
  243. # such that the encoder's padding tokens are not attended to.
  244. is_cross_attention = encoder_hidden_states is not None
  245. if is_cross_attention and past_key_value is not None:
  246. # reuse k,v, cross_attentions
  247. key_layer = past_key_value[0]
  248. value_layer = past_key_value[1]
  249. attention_mask = encoder_attention_mask
  250. elif is_cross_attention:
  251. key_layer = self.transpose_for_scores(self.key(inputs=encoder_hidden_states), batch_size)
  252. value_layer = self.transpose_for_scores(self.value(inputs=encoder_hidden_states), batch_size)
  253. attention_mask = encoder_attention_mask
  254. elif past_key_value is not None:
  255. key_layer = self.transpose_for_scores(self.key(inputs=hidden_states), batch_size)
  256. value_layer = self.transpose_for_scores(self.value(inputs=hidden_states), batch_size)
  257. key_layer = tf.concat([past_key_value[0], key_layer], axis=2)
  258. value_layer = tf.concat([past_key_value[1], value_layer], axis=2)
  259. else:
  260. key_layer = self.transpose_for_scores(self.key(inputs=hidden_states), batch_size)
  261. value_layer = self.transpose_for_scores(self.value(inputs=hidden_states), batch_size)
  262. query_layer = self.transpose_for_scores(mixed_query_layer, batch_size)
  263. if self.is_decoder:
  264. # if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states.
  265. # Further calls to cross_attention layer can then reuse all cross-attention
  266. # key/value_states (first "if" case)
  267. # if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of
  268. # all previous decoder key/value_states. Further calls to uni-directional self-attention
  269. # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
  270. # if encoder bi-directional self-attention `past_key_value` is always `None`
  271. past_key_value = (key_layer, value_layer)
  272. # Take the dot product between "query" and "key" to get the raw attention scores.
  273. # (batch size, num_heads, seq_len_q, seq_len_k)
  274. attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
  275. dk = tf.cast(self.sqrt_att_head_size, dtype=attention_scores.dtype)
  276. attention_scores = tf.divide(attention_scores, dk)
  277. if attention_mask is not None:
  278. # Apply the attention mask is (precomputed for all layers in TFTapasModel call() function)
  279. attention_scores = tf.add(attention_scores, attention_mask)
  280. # Normalize the attention scores to probabilities.
  281. attention_probs = stable_softmax(logits=attention_scores, axis=-1)
  282. # This is actually dropping out entire tokens to attend to, which might
  283. # seem a bit unusual, but is taken from the original Transformer paper.
  284. attention_probs = self.dropout(inputs=attention_probs, training=training)
  285. # Mask heads if we want to
  286. if head_mask is not None:
  287. attention_probs = tf.multiply(attention_probs, head_mask)
  288. attention_output = tf.matmul(attention_probs, value_layer)
  289. attention_output = tf.transpose(attention_output, perm=[0, 2, 1, 3])
  290. # (batch_size, seq_len_q, all_head_size)
  291. attention_output = tf.reshape(tensor=attention_output, shape=(batch_size, -1, self.all_head_size))
  292. outputs = (attention_output, attention_probs) if output_attentions else (attention_output,)
  293. if self.is_decoder:
  294. outputs = outputs + (past_key_value,)
  295. return outputs
  296. def build(self, input_shape=None):
  297. if self.built:
  298. return
  299. self.built = True
  300. if getattr(self, "query", None) is not None:
  301. with tf.name_scope(self.query.name):
  302. self.query.build([None, None, self.config.hidden_size])
  303. if getattr(self, "key", None) is not None:
  304. with tf.name_scope(self.key.name):
  305. self.key.build([None, None, self.config.hidden_size])
  306. if getattr(self, "value", None) is not None:
  307. with tf.name_scope(self.value.name):
  308. self.value.build([None, None, self.config.hidden_size])
  309. # Copied from transformers.models.bert.modeling_tf_bert.TFBertSelfOutput with Bert->Tapas
  310. class TFTapasSelfOutput(keras.layers.Layer):
  311. def __init__(self, config: TapasConfig, **kwargs):
  312. super().__init__(**kwargs)
  313. self.dense = keras.layers.Dense(
  314. units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
  315. )
  316. self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
  317. self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
  318. self.config = config
  319. def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
  320. hidden_states = self.dense(inputs=hidden_states)
  321. hidden_states = self.dropout(inputs=hidden_states, training=training)
  322. hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
  323. return hidden_states
  324. def build(self, input_shape=None):
  325. if self.built:
  326. return
  327. self.built = True
  328. if getattr(self, "dense", None) is not None:
  329. with tf.name_scope(self.dense.name):
  330. self.dense.build([None, None, self.config.hidden_size])
  331. if getattr(self, "LayerNorm", None) is not None:
  332. with tf.name_scope(self.LayerNorm.name):
  333. self.LayerNorm.build([None, None, self.config.hidden_size])
  334. # Copied from transformers.models.bert.modeling_tf_bert.TFBertAttention with Bert->Tapas
  335. class TFTapasAttention(keras.layers.Layer):
  336. def __init__(self, config: TapasConfig, **kwargs):
  337. super().__init__(**kwargs)
  338. self.self_attention = TFTapasSelfAttention(config, name="self")
  339. self.dense_output = TFTapasSelfOutput(config, name="output")
  340. def prune_heads(self, heads):
  341. raise NotImplementedError
  342. def call(
  343. self,
  344. input_tensor: tf.Tensor,
  345. attention_mask: tf.Tensor,
  346. head_mask: tf.Tensor,
  347. encoder_hidden_states: tf.Tensor,
  348. encoder_attention_mask: tf.Tensor,
  349. past_key_value: Tuple[tf.Tensor],
  350. output_attentions: bool,
  351. training: bool = False,
  352. ) -> Tuple[tf.Tensor]:
  353. self_outputs = self.self_attention(
  354. hidden_states=input_tensor,
  355. attention_mask=attention_mask,
  356. head_mask=head_mask,
  357. encoder_hidden_states=encoder_hidden_states,
  358. encoder_attention_mask=encoder_attention_mask,
  359. past_key_value=past_key_value,
  360. output_attentions=output_attentions,
  361. training=training,
  362. )
  363. attention_output = self.dense_output(
  364. hidden_states=self_outputs[0], input_tensor=input_tensor, training=training
  365. )
  366. # add attentions (possibly with past_key_value) if we output them
  367. outputs = (attention_output,) + self_outputs[1:]
  368. return outputs
  369. def build(self, input_shape=None):
  370. if self.built:
  371. return
  372. self.built = True
  373. if getattr(self, "self_attention", None) is not None:
  374. with tf.name_scope(self.self_attention.name):
  375. self.self_attention.build(None)
  376. if getattr(self, "dense_output", None) is not None:
  377. with tf.name_scope(self.dense_output.name):
  378. self.dense_output.build(None)
  379. # Copied from transformers.models.bert.modeling_tf_bert.TFBertIntermediate with Bert->Tapas
  380. class TFTapasIntermediate(keras.layers.Layer):
  381. def __init__(self, config: TapasConfig, **kwargs):
  382. super().__init__(**kwargs)
  383. self.dense = keras.layers.Dense(
  384. units=config.intermediate_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
  385. )
  386. if isinstance(config.hidden_act, str):
  387. self.intermediate_act_fn = get_tf_activation(config.hidden_act)
  388. else:
  389. self.intermediate_act_fn = config.hidden_act
  390. self.config = config
  391. def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
  392. hidden_states = self.dense(inputs=hidden_states)
  393. hidden_states = self.intermediate_act_fn(hidden_states)
  394. return hidden_states
  395. def build(self, input_shape=None):
  396. if self.built:
  397. return
  398. self.built = True
  399. if getattr(self, "dense", None) is not None:
  400. with tf.name_scope(self.dense.name):
  401. self.dense.build([None, None, self.config.hidden_size])
  402. # Copied from transformers.models.bert.modeling_tf_bert.TFBertOutput with Bert->Tapas
  403. class TFTapasOutput(keras.layers.Layer):
  404. def __init__(self, config: TapasConfig, **kwargs):
  405. super().__init__(**kwargs)
  406. self.dense = keras.layers.Dense(
  407. units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
  408. )
  409. self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
  410. self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
  411. self.config = config
  412. def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
  413. hidden_states = self.dense(inputs=hidden_states)
  414. hidden_states = self.dropout(inputs=hidden_states, training=training)
  415. hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
  416. return hidden_states
  417. def build(self, input_shape=None):
  418. if self.built:
  419. return
  420. self.built = True
  421. if getattr(self, "dense", None) is not None:
  422. with tf.name_scope(self.dense.name):
  423. self.dense.build([None, None, self.config.intermediate_size])
  424. if getattr(self, "LayerNorm", None) is not None:
  425. with tf.name_scope(self.LayerNorm.name):
  426. self.LayerNorm.build([None, None, self.config.hidden_size])
  427. # Copied from transformers.models.bert.modeling_tf_bert.TFBertLayer with Bert->Tapas
  428. class TFTapasLayer(keras.layers.Layer):
  429. def __init__(self, config: TapasConfig, **kwargs):
  430. super().__init__(**kwargs)
  431. self.attention = TFTapasAttention(config, name="attention")
  432. self.is_decoder = config.is_decoder
  433. self.add_cross_attention = config.add_cross_attention
  434. if self.add_cross_attention:
  435. if not self.is_decoder:
  436. raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
  437. self.crossattention = TFTapasAttention(config, name="crossattention")
  438. self.intermediate = TFTapasIntermediate(config, name="intermediate")
  439. self.bert_output = TFTapasOutput(config, name="output")
  440. def call(
  441. self,
  442. hidden_states: tf.Tensor,
  443. attention_mask: tf.Tensor,
  444. head_mask: tf.Tensor,
  445. encoder_hidden_states: tf.Tensor | None,
  446. encoder_attention_mask: tf.Tensor | None,
  447. past_key_value: Tuple[tf.Tensor] | None,
  448. output_attentions: bool,
  449. training: bool = False,
  450. ) -> Tuple[tf.Tensor]:
  451. # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
  452. self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
  453. self_attention_outputs = self.attention(
  454. input_tensor=hidden_states,
  455. attention_mask=attention_mask,
  456. head_mask=head_mask,
  457. encoder_hidden_states=None,
  458. encoder_attention_mask=None,
  459. past_key_value=self_attn_past_key_value,
  460. output_attentions=output_attentions,
  461. training=training,
  462. )
  463. attention_output = self_attention_outputs[0]
  464. # if decoder, the last output is tuple of self-attn cache
  465. if self.is_decoder:
  466. outputs = self_attention_outputs[1:-1]
  467. present_key_value = self_attention_outputs[-1]
  468. else:
  469. outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
  470. cross_attn_present_key_value = None
  471. if self.is_decoder and encoder_hidden_states is not None:
  472. if not hasattr(self, "crossattention"):
  473. raise ValueError(
  474. f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
  475. " by setting `config.add_cross_attention=True`"
  476. )
  477. # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
  478. cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
  479. cross_attention_outputs = self.crossattention(
  480. input_tensor=attention_output,
  481. attention_mask=attention_mask,
  482. head_mask=head_mask,
  483. encoder_hidden_states=encoder_hidden_states,
  484. encoder_attention_mask=encoder_attention_mask,
  485. past_key_value=cross_attn_past_key_value,
  486. output_attentions=output_attentions,
  487. training=training,
  488. )
  489. attention_output = cross_attention_outputs[0]
  490. outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
  491. # add cross-attn cache to positions 3,4 of present_key_value tuple
  492. cross_attn_present_key_value = cross_attention_outputs[-1]
  493. present_key_value = present_key_value + cross_attn_present_key_value
  494. intermediate_output = self.intermediate(hidden_states=attention_output)
  495. layer_output = self.bert_output(
  496. hidden_states=intermediate_output, input_tensor=attention_output, training=training
  497. )
  498. outputs = (layer_output,) + outputs # add attentions if we output them
  499. # if decoder, return the attn key/values as the last output
  500. if self.is_decoder:
  501. outputs = outputs + (present_key_value,)
  502. return outputs
  503. def build(self, input_shape=None):
  504. if self.built:
  505. return
  506. self.built = True
  507. if getattr(self, "attention", None) is not None:
  508. with tf.name_scope(self.attention.name):
  509. self.attention.build(None)
  510. if getattr(self, "intermediate", None) is not None:
  511. with tf.name_scope(self.intermediate.name):
  512. self.intermediate.build(None)
  513. if getattr(self, "bert_output", None) is not None:
  514. with tf.name_scope(self.bert_output.name):
  515. self.bert_output.build(None)
  516. if getattr(self, "crossattention", None) is not None:
  517. with tf.name_scope(self.crossattention.name):
  518. self.crossattention.build(None)
  519. # Copied from transformers.models.bert.modeling_tf_bert.TFBertEncoder with Bert->Tapas
  520. class TFTapasEncoder(keras.layers.Layer):
  521. def __init__(self, config: TapasConfig, **kwargs):
  522. super().__init__(**kwargs)
  523. self.config = config
  524. self.layer = [TFTapasLayer(config, name=f"layer_._{i}") for i in range(config.num_hidden_layers)]
  525. def call(
  526. self,
  527. hidden_states: tf.Tensor,
  528. attention_mask: tf.Tensor,
  529. head_mask: tf.Tensor,
  530. encoder_hidden_states: tf.Tensor | None,
  531. encoder_attention_mask: tf.Tensor | None,
  532. past_key_values: Tuple[Tuple[tf.Tensor]] | None,
  533. use_cache: Optional[bool],
  534. output_attentions: bool,
  535. output_hidden_states: bool,
  536. return_dict: bool,
  537. training: bool = False,
  538. ) -> Union[TFBaseModelOutputWithPastAndCrossAttentions, Tuple[tf.Tensor]]:
  539. all_hidden_states = () if output_hidden_states else None
  540. all_attentions = () if output_attentions else None
  541. all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
  542. next_decoder_cache = () if use_cache else None
  543. for i, layer_module in enumerate(self.layer):
  544. if output_hidden_states:
  545. all_hidden_states = all_hidden_states + (hidden_states,)
  546. past_key_value = past_key_values[i] if past_key_values is not None else None
  547. layer_outputs = layer_module(
  548. hidden_states=hidden_states,
  549. attention_mask=attention_mask,
  550. head_mask=head_mask[i],
  551. encoder_hidden_states=encoder_hidden_states,
  552. encoder_attention_mask=encoder_attention_mask,
  553. past_key_value=past_key_value,
  554. output_attentions=output_attentions,
  555. training=training,
  556. )
  557. hidden_states = layer_outputs[0]
  558. if use_cache:
  559. next_decoder_cache += (layer_outputs[-1],)
  560. if output_attentions:
  561. all_attentions = all_attentions + (layer_outputs[1],)
  562. if self.config.add_cross_attention and encoder_hidden_states is not None:
  563. all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
  564. # Add last layer
  565. if output_hidden_states:
  566. all_hidden_states = all_hidden_states + (hidden_states,)
  567. if not return_dict:
  568. return tuple(
  569. v for v in [hidden_states, all_hidden_states, all_attentions, all_cross_attentions] if v is not None
  570. )
  571. return TFBaseModelOutputWithPastAndCrossAttentions(
  572. last_hidden_state=hidden_states,
  573. past_key_values=next_decoder_cache,
  574. hidden_states=all_hidden_states,
  575. attentions=all_attentions,
  576. cross_attentions=all_cross_attentions,
  577. )
  578. def build(self, input_shape=None):
  579. if self.built:
  580. return
  581. self.built = True
  582. if getattr(self, "layer", None) is not None:
  583. for layer in self.layer:
  584. with tf.name_scope(layer.name):
  585. layer.build(None)
  586. # Copied from transformers.models.bert.modeling_tf_bert.TFBertPooler with Bert->Tapas
  587. class TFTapasPooler(keras.layers.Layer):
  588. def __init__(self, config: TapasConfig, **kwargs):
  589. super().__init__(**kwargs)
  590. self.dense = keras.layers.Dense(
  591. units=config.hidden_size,
  592. kernel_initializer=get_initializer(config.initializer_range),
  593. activation="tanh",
  594. name="dense",
  595. )
  596. self.config = config
  597. def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
  598. # We "pool" the model by simply taking the hidden state corresponding
  599. # to the first token.
  600. first_token_tensor = hidden_states[:, 0]
  601. pooled_output = self.dense(inputs=first_token_tensor)
  602. return pooled_output
  603. def build(self, input_shape=None):
  604. if self.built:
  605. return
  606. self.built = True
  607. if getattr(self, "dense", None) is not None:
  608. with tf.name_scope(self.dense.name):
  609. self.dense.build([None, None, self.config.hidden_size])
  610. # Copied from transformers.models.bert.modeling_tf_bert.TFBertPredictionHeadTransform with Bert->Tapas
  611. class TFTapasPredictionHeadTransform(keras.layers.Layer):
  612. def __init__(self, config: TapasConfig, **kwargs):
  613. super().__init__(**kwargs)
  614. self.dense = keras.layers.Dense(
  615. units=config.hidden_size,
  616. kernel_initializer=get_initializer(config.initializer_range),
  617. name="dense",
  618. )
  619. if isinstance(config.hidden_act, str):
  620. self.transform_act_fn = get_tf_activation(config.hidden_act)
  621. else:
  622. self.transform_act_fn = config.hidden_act
  623. self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
  624. self.config = config
  625. def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
  626. hidden_states = self.dense(inputs=hidden_states)
  627. hidden_states = self.transform_act_fn(hidden_states)
  628. hidden_states = self.LayerNorm(inputs=hidden_states)
  629. return hidden_states
  630. def build(self, input_shape=None):
  631. if self.built:
  632. return
  633. self.built = True
  634. if getattr(self, "dense", None) is not None:
  635. with tf.name_scope(self.dense.name):
  636. self.dense.build([None, None, self.config.hidden_size])
  637. if getattr(self, "LayerNorm", None) is not None:
  638. with tf.name_scope(self.LayerNorm.name):
  639. self.LayerNorm.build([None, None, self.config.hidden_size])
  640. # Copied from transformers.models.bert.modeling_tf_bert.TFBertLMPredictionHead with Bert->Tapas
  641. class TFTapasLMPredictionHead(keras.layers.Layer):
  642. def __init__(self, config: TapasConfig, input_embeddings: keras.layers.Layer, **kwargs):
  643. super().__init__(**kwargs)
  644. self.config = config
  645. self.hidden_size = config.hidden_size
  646. self.transform = TFTapasPredictionHeadTransform(config, name="transform")
  647. # The output weights are the same as the input embeddings, but there is
  648. # an output-only bias for each token.
  649. self.input_embeddings = input_embeddings
  650. def build(self, input_shape=None):
  651. self.bias = self.add_weight(shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="bias")
  652. if self.built:
  653. return
  654. self.built = True
  655. if getattr(self, "transform", None) is not None:
  656. with tf.name_scope(self.transform.name):
  657. self.transform.build(None)
  658. def get_output_embeddings(self) -> keras.layers.Layer:
  659. return self.input_embeddings
  660. def set_output_embeddings(self, value: tf.Variable):
  661. self.input_embeddings.weight = value
  662. self.input_embeddings.vocab_size = shape_list(value)[0]
  663. def get_bias(self) -> Dict[str, tf.Variable]:
  664. return {"bias": self.bias}
  665. def set_bias(self, value: tf.Variable):
  666. self.bias = value["bias"]
  667. self.config.vocab_size = shape_list(value["bias"])[0]
  668. def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
  669. hidden_states = self.transform(hidden_states=hidden_states)
  670. seq_length = shape_list(hidden_states)[1]
  671. hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, self.hidden_size])
  672. hidden_states = tf.matmul(a=hidden_states, b=self.input_embeddings.weight, transpose_b=True)
  673. hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, seq_length, self.config.vocab_size])
  674. hidden_states = tf.nn.bias_add(value=hidden_states, bias=self.bias)
  675. return hidden_states
  676. # Copied from transformers.models.bert.modeling_tf_bert.TFBertMLMHead with Bert->Tapas
  677. class TFTapasMLMHead(keras.layers.Layer):
  678. def __init__(self, config: TapasConfig, input_embeddings: keras.layers.Layer, **kwargs):
  679. super().__init__(**kwargs)
  680. self.predictions = TFTapasLMPredictionHead(config, input_embeddings, name="predictions")
  681. def call(self, sequence_output: tf.Tensor) -> tf.Tensor:
  682. prediction_scores = self.predictions(hidden_states=sequence_output)
  683. return prediction_scores
  684. def build(self, input_shape=None):
  685. if self.built:
  686. return
  687. self.built = True
  688. if getattr(self, "predictions", None) is not None:
  689. with tf.name_scope(self.predictions.name):
  690. self.predictions.build(None)
  691. @keras_serializable
  692. class TFTapasMainLayer(keras.layers.Layer):
  693. config_class = TapasConfig
  694. def __init__(self, config: TapasConfig, add_pooling_layer: bool = True, **kwargs):
  695. super().__init__(**kwargs)
  696. self.config = config
  697. self.embeddings = TFTapasEmbeddings(config, name="embeddings")
  698. self.encoder = TFTapasEncoder(config, name="encoder")
  699. self.pooler = TFTapasPooler(config, name="pooler") if add_pooling_layer else None
  700. def get_input_embeddings(self) -> keras.layers.Layer:
  701. return self.embeddings
  702. def set_input_embeddings(self, value: tf.Variable):
  703. self.embeddings.weight = value
  704. self.embeddings.vocab_size = shape_list(value)[0]
  705. def _prune_heads(self, heads_to_prune):
  706. """
  707. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
  708. class PreTrainedModel
  709. """
  710. raise NotImplementedError
  711. @unpack_inputs
  712. def call(
  713. self,
  714. input_ids: TFModelInputType | None = None,
  715. attention_mask: np.ndarray | tf.Tensor | None = None,
  716. token_type_ids: np.ndarray | tf.Tensor | None = None,
  717. position_ids: np.ndarray | tf.Tensor | None = None,
  718. head_mask: np.ndarray | tf.Tensor | None = None,
  719. inputs_embeds: np.ndarray | tf.Tensor | None = None,
  720. output_attentions: Optional[bool] = None,
  721. output_hidden_states: Optional[bool] = None,
  722. return_dict: Optional[bool] = None,
  723. training: bool = False,
  724. ) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]:
  725. if input_ids is not None and inputs_embeds is not None:
  726. raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
  727. elif input_ids is not None:
  728. input_shape = shape_list(input_ids)
  729. elif inputs_embeds is not None:
  730. input_shape = shape_list(inputs_embeds)[:-1]
  731. else:
  732. raise ValueError("You have to specify either input_ids or inputs_embeds")
  733. if attention_mask is None:
  734. attention_mask = tf.fill(dims=input_shape, value=1)
  735. if token_type_ids is None:
  736. token_type_ids = tf.fill(dims=input_shape + [len(self.config.type_vocab_sizes)], value=0)
  737. embedding_output = self.embeddings(
  738. input_ids=input_ids,
  739. position_ids=position_ids,
  740. token_type_ids=token_type_ids,
  741. inputs_embeds=inputs_embeds,
  742. training=training,
  743. )
  744. # We create a 3D attention mask from a 2D tensor mask.
  745. # Sizes are [batch_size, 1, 1, to_seq_length]
  746. # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
  747. # this attention mask is more simple than the triangular masking of causal attention
  748. # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
  749. extended_attention_mask = tf.reshape(attention_mask, (input_shape[0], 1, 1, input_shape[1]))
  750. # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
  751. # masked positions, this operation will create a tensor which is 0.0 for
  752. # positions we want to attend and -10000.0 for masked positions.
  753. # Since we are adding it to the raw scores before the softmax, this is
  754. # effectively the same as removing these entirely.
  755. extended_attention_mask = tf.cast(extended_attention_mask, dtype=embedding_output.dtype)
  756. one_cst = tf.constant(1.0, dtype=embedding_output.dtype)
  757. ten_thousand_cst = tf.constant(-10000.0, dtype=embedding_output.dtype)
  758. extended_attention_mask = tf.multiply(tf.subtract(one_cst, extended_attention_mask), ten_thousand_cst)
  759. # Prepare head mask if needed
  760. # 1.0 in head_mask indicate we keep the head
  761. # attention_probs has shape bsz x n_heads x N x N
  762. # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
  763. # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
  764. if head_mask is not None:
  765. raise NotImplementedError
  766. else:
  767. head_mask = [None] * self.config.num_hidden_layers
  768. encoder_outputs = self.encoder(
  769. hidden_states=embedding_output,
  770. attention_mask=extended_attention_mask,
  771. head_mask=head_mask,
  772. encoder_hidden_states=None,
  773. encoder_attention_mask=None,
  774. past_key_values=None,
  775. use_cache=None,
  776. output_attentions=output_attentions,
  777. output_hidden_states=output_hidden_states,
  778. return_dict=return_dict,
  779. training=training,
  780. )
  781. sequence_output = encoder_outputs[0]
  782. pooled_output = self.pooler(hidden_states=sequence_output) if self.pooler is not None else None
  783. if not return_dict:
  784. return (
  785. sequence_output,
  786. pooled_output,
  787. ) + encoder_outputs[1:]
  788. return TFBaseModelOutputWithPooling(
  789. last_hidden_state=sequence_output,
  790. pooler_output=pooled_output,
  791. hidden_states=encoder_outputs.hidden_states,
  792. attentions=encoder_outputs.attentions,
  793. )
  794. def build(self, input_shape=None):
  795. if self.built:
  796. return
  797. self.built = True
  798. if getattr(self, "embeddings", None) is not None:
  799. with tf.name_scope(self.embeddings.name):
  800. self.embeddings.build(None)
  801. if getattr(self, "encoder", None) is not None:
  802. with tf.name_scope(self.encoder.name):
  803. self.encoder.build(None)
  804. if getattr(self, "pooler", None) is not None:
  805. with tf.name_scope(self.pooler.name):
  806. self.pooler.build(None)
  807. class TFTapasPreTrainedModel(TFPreTrainedModel):
  808. """
  809. An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
  810. models.
  811. """
  812. config_class = TapasConfig
  813. base_model_prefix = "tapas"
  814. @property
  815. def input_signature(self):
  816. return {
  817. "input_ids": tf.TensorSpec((None, None), tf.int32, name="input_ids"),
  818. "attention_mask": tf.TensorSpec((None, None), tf.float32, name="attention_mask"),
  819. "token_type_ids": tf.TensorSpec((None, None, 7), tf.int32, name="token_type_ids"),
  820. }
  821. TAPAS_START_DOCSTRING = r"""
  822. This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
  823. library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
  824. etc.)
  825. This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
  826. as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
  827. behavior.
  828. <Tip>
  829. TensorFlow models and layers in `transformers` accept two formats as input:
  830. - having all inputs as keyword arguments (like PyTorch models), or
  831. - having all inputs as a list, tuple or dict in the first positional argument.
  832. The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
  833. and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
  834. pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
  835. format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
  836. the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
  837. positional argument:
  838. - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
  839. - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
  840. `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
  841. - a dictionary with one or several input Tensors associated to the input names given in the docstring:
  842. `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
  843. Note that when creating models and layers with
  844. [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
  845. about any of this, as you can just pass inputs like you would to any other Python function!
  846. </Tip>
  847. Parameters:
  848. config ([`TapasConfig`]): Model configuration class with all the parameters of the model.
  849. Initializing with a config file does not load the weights associated with the model, only the
  850. configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
  851. """
  852. TAPAS_INPUTS_DOCSTRING = r"""
  853. Args:
  854. 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})`):
  855. Indices of input sequence tokens in the vocabulary.
  856. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
  857. [`PreTrainedTokenizer.encode`] for details.
  858. [What are input IDs?](../glossary#input-ids)
  859. attention_mask (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
  860. Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
  861. - 1 for tokens that are **not masked**,
  862. - 0 for tokens that are **masked**.
  863. [What are attention masks?](../glossary#attention-mask)
  864. token_type_ids (`np.ndarray` or `tf.Tensor` of shape `({0}, 7)`, *optional*):
  865. Token indices that encode tabular structure. Indices can be obtained using [`AutoTokenizer`]. See this
  866. class for more info.
  867. [What are token type IDs?](../glossary#token-type-ids)
  868. position_ids (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
  869. Indices of positions of each input sequence tokens in the position embeddings. If
  870. `reset_position_index_per_cell` of [`TapasConfig`] is set to `True`, relative position embeddings will be
  871. used. Selected in the range `[0, config.max_position_embeddings - 1]`.
  872. [What are position IDs?](../glossary#position-ids)
  873. head_mask (`np.ndarray` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
  874. Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
  875. - 1 indicates the head is **not masked**,
  876. - 0 indicates the head is **masked**.
  877. inputs_embeds (`np.ndarray` or `tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
  878. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  879. is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
  880. model's internal embedding lookup matrix.
  881. output_attentions (`bool`, *optional*):
  882. Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
  883. tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
  884. config will be used instead.
  885. output_hidden_states (`bool`, *optional*):
  886. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
  887. more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
  888. used instead.
  889. return_dict (`bool`, *optional*):
  890. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
  891. eager mode, in graph mode the value will always be set to True.
  892. training (`bool`, *optional*, defaults to `False``):
  893. Whether or not to use the model in training mode (some modules like dropout modules have different
  894. behaviors between training and evaluation).
  895. """
  896. @add_start_docstrings(
  897. "The bare Tapas Model transformer outputting raw hidden-states without any specific head on top.",
  898. TAPAS_START_DOCSTRING,
  899. )
  900. class TFTapasModel(TFTapasPreTrainedModel):
  901. def __init__(self, config: TapasConfig, *inputs, **kwargs):
  902. super().__init__(config, *inputs, **kwargs)
  903. self.tapas = TFTapasMainLayer(config, name="tapas")
  904. @unpack_inputs
  905. @add_start_docstrings_to_model_forward(TAPAS_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
  906. @replace_return_docstrings(output_type=TFBaseModelOutputWithPooling, config_class=_CONFIG_FOR_DOC)
  907. def call(
  908. self,
  909. input_ids: TFModelInputType | None = None,
  910. attention_mask: np.ndarray | tf.Tensor | None = None,
  911. token_type_ids: np.ndarray | tf.Tensor | None = None,
  912. position_ids: np.ndarray | tf.Tensor | None = None,
  913. head_mask: np.ndarray | tf.Tensor | None = None,
  914. inputs_embeds: np.ndarray | tf.Tensor | None = None,
  915. output_attentions: Optional[bool] = None,
  916. output_hidden_states: Optional[bool] = None,
  917. return_dict: Optional[bool] = None,
  918. training: Optional[bool] = False,
  919. ) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]:
  920. r"""
  921. Returns:
  922. Examples:
  923. ```python
  924. >>> from transformers import AutoTokenizer, TapasModel
  925. >>> import pandas as pd
  926. >>> tokenizer = AutoTokenizer.from_pretrained("google/tapas-base")
  927. >>> model = TapasModel.from_pretrained("google/tapas-base")
  928. >>> data = {
  929. ... "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"],
  930. ... "Age": ["56", "45", "59"],
  931. ... "Number of movies": ["87", "53", "69"],
  932. ... }
  933. >>> table = pd.DataFrame.from_dict(data)
  934. >>> queries = ["How many movies has George Clooney played in?", "How old is Brad Pitt?"]
  935. >>> inputs = tokenizer(table=table, queries=queries, padding="max_length", return_tensors="tf")
  936. >>> outputs = model(**inputs)
  937. >>> last_hidden_states = outputs.last_hidden_state
  938. ```"""
  939. outputs = self.tapas(
  940. input_ids=input_ids,
  941. attention_mask=attention_mask,
  942. token_type_ids=token_type_ids,
  943. position_ids=position_ids,
  944. head_mask=head_mask,
  945. inputs_embeds=inputs_embeds,
  946. output_attentions=output_attentions,
  947. output_hidden_states=output_hidden_states,
  948. return_dict=return_dict,
  949. training=training,
  950. )
  951. return outputs
  952. def build(self, input_shape=None):
  953. if self.built:
  954. return
  955. self.built = True
  956. if getattr(self, "tapas", None) is not None:
  957. with tf.name_scope(self.tapas.name):
  958. self.tapas.build(None)
  959. @add_start_docstrings("""Tapas Model with a `language modeling` head on top.""", TAPAS_START_DOCSTRING)
  960. class TFTapasForMaskedLM(TFTapasPreTrainedModel, TFMaskedLanguageModelingLoss):
  961. def __init__(self, config: TapasConfig, *inputs, **kwargs):
  962. super().__init__(config, *inputs, **kwargs)
  963. if config.is_decoder:
  964. logger.warning(
  965. "If you want to use `TFTapasForMaskedLM` make sure `config.is_decoder=False` for "
  966. "bi-directional self-attention."
  967. )
  968. self.tapas = TFTapasMainLayer(config, add_pooling_layer=False, name="tapas")
  969. self.lm_head = TFTapasMLMHead(config, input_embeddings=self.tapas.embeddings, name="cls")
  970. def get_lm_head(self) -> keras.layers.Layer:
  971. return self.lm_head.predictions
  972. @unpack_inputs
  973. @add_start_docstrings_to_model_forward(TAPAS_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
  974. @replace_return_docstrings(output_type=TFMaskedLMOutput, config_class=_CONFIG_FOR_DOC)
  975. def call(
  976. self,
  977. input_ids: TFModelInputType | None = None,
  978. attention_mask: np.ndarray | tf.Tensor | None = None,
  979. token_type_ids: np.ndarray | tf.Tensor | None = None,
  980. position_ids: np.ndarray | tf.Tensor | None = None,
  981. head_mask: np.ndarray | tf.Tensor | None = None,
  982. inputs_embeds: np.ndarray | tf.Tensor | None = None,
  983. output_attentions: Optional[bool] = None,
  984. output_hidden_states: Optional[bool] = None,
  985. return_dict: Optional[bool] = None,
  986. labels: np.ndarray | tf.Tensor | None = None,
  987. training: Optional[bool] = False,
  988. ) -> Union[TFMaskedLMOutput, Tuple[tf.Tensor]]:
  989. r"""
  990. labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
  991. Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
  992. config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
  993. loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
  994. Returns:
  995. Examples:
  996. ```python
  997. >>> from transformers import AutoTokenizer, TapasForMaskedLM
  998. >>> import pandas as pd
  999. >>> tokenizer = AutoTokenizer.from_pretrained("google/tapas-base")
  1000. >>> model = TapasForMaskedLM.from_pretrained("google/tapas-base")
  1001. >>> data = {
  1002. ... "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"],
  1003. ... "Age": ["56", "45", "59"],
  1004. ... "Number of movies": ["87", "53", "69"],
  1005. ... }
  1006. >>> table = pd.DataFrame.from_dict(data)
  1007. >>> inputs = tokenizer(
  1008. ... table=table, queries="How many [MASK] has George [MASK] played in?", return_tensors="tf"
  1009. ... )
  1010. >>> labels = tokenizer(
  1011. ... table=table, queries="How many movies has George Clooney played in?", return_tensors="tf"
  1012. ... )["input_ids"]
  1013. >>> outputs = model(**inputs, labels=labels)
  1014. >>> logits = outputs.logits
  1015. ```"""
  1016. outputs = self.tapas(
  1017. input_ids=input_ids,
  1018. attention_mask=attention_mask,
  1019. token_type_ids=token_type_ids,
  1020. position_ids=position_ids,
  1021. head_mask=head_mask,
  1022. inputs_embeds=inputs_embeds,
  1023. output_attentions=output_attentions,
  1024. output_hidden_states=output_hidden_states,
  1025. return_dict=return_dict,
  1026. training=training,
  1027. )
  1028. sequence_output = outputs[0]
  1029. prediction_scores = self.lm_head(sequence_output)
  1030. loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=prediction_scores)
  1031. if not return_dict:
  1032. output = (prediction_scores,) + outputs[2:]
  1033. return ((loss,) + output) if loss is not None else output
  1034. return TFMaskedLMOutput(
  1035. loss=loss,
  1036. logits=prediction_scores,
  1037. hidden_states=outputs.hidden_states,
  1038. attentions=outputs.attentions,
  1039. )
  1040. def build(self, input_shape=None):
  1041. if self.built:
  1042. return
  1043. self.built = True
  1044. if getattr(self, "tapas", None) is not None:
  1045. with tf.name_scope(self.tapas.name):
  1046. self.tapas.build(None)
  1047. if getattr(self, "lm_head", None) is not None:
  1048. with tf.name_scope(self.lm_head.name):
  1049. self.lm_head.build(None)
  1050. class TFTapasComputeTokenLogits(keras.layers.Layer):
  1051. def __init__(self, config: TapasConfig, **kwargs):
  1052. super().__init__(**kwargs)
  1053. self.temperature = config.temperature
  1054. # cell selection heads
  1055. with tf.name_scope("output"):
  1056. self.output_weights = self.add_weight(
  1057. name="output_weights",
  1058. shape=(config.hidden_size,),
  1059. dtype=tf.float32,
  1060. trainable=True,
  1061. initializer=tf.zeros_initializer()
  1062. if config.init_cell_selection_weights_to_zero
  1063. else keras.initializers.TruncatedNormal(stddev=config.initializer_range),
  1064. )
  1065. self.output_bias = self.add_weight(
  1066. name="output_bias", shape=(), trainable=True, initializer=tf.zeros_initializer()
  1067. )
  1068. def call(self, sequence_output: tf.Tensor) -> tf.Tensor:
  1069. """
  1070. Computes logits per token
  1071. Args:
  1072. sequence_output (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
  1073. Also known as last_hidden_state. Sequence of hidden-states at the output of the last layer of the
  1074. model.
  1075. Returns:
  1076. logits (`tf.Tensor` of shape `(batch_size, sequence_length)`): Logits per token.
  1077. """
  1078. logits = (tf.einsum("bsj,j->bs", sequence_output, self.output_weights) + self.output_bias) / self.temperature
  1079. return logits
  1080. class TFTapasComputeColumnLogits(keras.layers.Layer):
  1081. def __init__(self, config: TapasConfig, **kwargs):
  1082. super().__init__(**kwargs)
  1083. with tf.name_scope("column_output"):
  1084. self.column_output_weights = self.add_weight(
  1085. name="column_output_weights",
  1086. shape=[config.hidden_size],
  1087. dtype=tf.float32,
  1088. trainable=True,
  1089. initializer=tf.zeros_initializer()
  1090. if config.init_cell_selection_weights_to_zero
  1091. else keras.initializers.TruncatedNormal(stddev=config.initializer_range),
  1092. )
  1093. self.column_output_bias = self.add_weight(
  1094. name="column_output_bias", shape=(), trainable=True, initializer=tf.zeros_initializer()
  1095. )
  1096. def call(self, sequence_output, cell_index, cell_mask, allow_empty_column_selection) -> tf.Tensor:
  1097. """
  1098. Computes the column logits.
  1099. Args:
  1100. sequence_output (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
  1101. Also known as last_hidden_state. Sequence of hidden-states at the output of the last layer of the
  1102. model.
  1103. cell_index (`ProductIndexMap`):
  1104. Index that groups tokens into cells.
  1105. cell_mask (`tf.Tensor` of shape `(batch_size, max_num_rows * max_num_cols)`):
  1106. Mask for cells that exist in the table (i.e. that are not padding).
  1107. allow_empty_column_selection (`bool`):
  1108. Whether to allow not to select any column
  1109. Returns:
  1110. column_logits (`tf.Tensor`of shape `(batch_size, max_num_cols)`): Tensor containing the column logits for
  1111. every example in the batch.
  1112. """
  1113. # First, compute the token logits (batch_size, seq_len) - without temperature
  1114. token_logits = tf.einsum("bsj,j->bs", sequence_output, self.column_output_weights) + self.column_output_bias
  1115. # Next, average the logits per cell (batch_size, max_num_cols*max_num_rows)
  1116. cell_logits, cell_logits_index = reduce_mean(token_logits, cell_index)
  1117. # Finally, average the logits per column (batch_size, max_num_cols)
  1118. column_index = cell_index.project_inner(cell_logits_index)
  1119. column_logits, out_index = reduce_sum(cell_logits * cell_mask, column_index)
  1120. cell_count, _ = reduce_sum(cell_mask, column_index)
  1121. column_logits /= cell_count + EPSILON_ZERO_DIVISION
  1122. # Mask columns that do not appear in the example.
  1123. is_padding = tf.logical_and(cell_count < 0.5, tf.not_equal(out_index.indices, 0))
  1124. column_logits += CLOSE_ENOUGH_TO_LOG_ZERO * tf.cast(is_padding, tf.float32)
  1125. if not allow_empty_column_selection:
  1126. column_logits += CLOSE_ENOUGH_TO_LOG_ZERO * tf.cast(tf.equal(out_index.indices, 0), tf.float32)
  1127. return column_logits
  1128. @add_start_docstrings(
  1129. """
  1130. Tapas Model with a cell selection head and optional aggregation head on top for question-answering tasks on tables
  1131. (linear layers on top of the hidden-states output to compute `logits` and optional `logits_aggregation`), e.g. for
  1132. SQA, WTQ or WikiSQL-supervised tasks.
  1133. """,
  1134. TAPAS_START_DOCSTRING,
  1135. )
  1136. class TFTapasForQuestionAnswering(TFTapasPreTrainedModel):
  1137. def __init__(self, config: TapasConfig, *inputs, **kwargs):
  1138. super().__init__(config, *inputs, **kwargs)
  1139. # base model
  1140. self.tapas = TFTapasMainLayer(config, name="tapas")
  1141. # dropout
  1142. self.dropout = keras.layers.Dropout(config.hidden_dropout_prob)
  1143. self.compute_token_logits = TFTapasComputeTokenLogits(config, name="compute_token_logits")
  1144. self.compute_column_logits = TFTapasComputeColumnLogits(config, name="compute_column_logits")
  1145. if config.num_aggregation_labels > 0:
  1146. self.aggregation_classifier = keras.layers.Dense(
  1147. config.num_aggregation_labels,
  1148. kernel_initializer=get_initializer(config.initializer_range),
  1149. name="aggregation_classifier",
  1150. )
  1151. self.config = config
  1152. @unpack_inputs
  1153. @add_start_docstrings_to_model_forward(TAPAS_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
  1154. @replace_return_docstrings(output_type=TFTableQuestionAnsweringOutput, config_class=_CONFIG_FOR_DOC)
  1155. def call(
  1156. self,
  1157. input_ids: TFModelInputType | None = None,
  1158. attention_mask: np.ndarray | tf.Tensor | None = None,
  1159. token_type_ids: np.ndarray | tf.Tensor | None = None,
  1160. position_ids: np.ndarray | tf.Tensor | None = None,
  1161. head_mask: np.ndarray | tf.Tensor | None = None,
  1162. inputs_embeds: np.ndarray | tf.Tensor | None = None,
  1163. table_mask: np.ndarray | tf.Tensor | None = None,
  1164. aggregation_labels: np.ndarray | tf.Tensor | None = None,
  1165. float_answer: np.ndarray | tf.Tensor | None = None,
  1166. numeric_values: np.ndarray | tf.Tensor | None = None,
  1167. numeric_values_scale: np.ndarray | tf.Tensor | None = None,
  1168. output_attentions: Optional[bool] = None,
  1169. output_hidden_states: Optional[bool] = None,
  1170. return_dict: Optional[bool] = None,
  1171. labels: np.ndarray | tf.Tensor | None = None,
  1172. training: Optional[bool] = False,
  1173. ) -> Union[TFTableQuestionAnsweringOutput, Tuple[tf.Tensor]]:
  1174. r"""
  1175. table_mask (`tf.Tensor` of shape `(batch_size, seq_length)`, *optional*):
  1176. Mask for the table. Indicates which tokens belong to the table (1). Question tokens, table headers and
  1177. padding are 0.
  1178. labels (`tf.Tensor` of shape `(batch_size, seq_length)`, *optional*):
  1179. Labels per token for computing the hierarchical cell selection loss. This encodes the positions of the
  1180. answer appearing in the table. Can be obtained using [`AutoTokenizer`].
  1181. - 1 for tokens that are **part of the answer**,
  1182. - 0 for tokens that are **not part of the answer**.
  1183. aggregation_labels (`tf.Tensor` of shape `(batch_size, )`, *optional*):
  1184. Aggregation function index for every example in the batch for computing the aggregation loss. Indices
  1185. should be in `[0, ..., config.num_aggregation_labels - 1]`. Only required in case of strong supervision for
  1186. aggregation (WikiSQL-supervised).
  1187. float_answer (`tf.Tensor` of shape `(batch_size, )`, *optional*):
  1188. Float answer for every example in the batch. Set to *float('nan')* for cell selection questions. Only
  1189. required in case of weak supervision (WTQ) to calculate the aggregate mask and regression loss.
  1190. numeric_values (`tf.Tensor` of shape `(batch_size, seq_length)`, *optional*):
  1191. Numeric values of every token, NaN for tokens which are not numeric values. Can be obtained using
  1192. [`AutoTokenizer`]. Only required in case of weak supervision for aggregation (WTQ) to calculate the
  1193. regression loss.
  1194. numeric_values_scale (`tf.Tensor` of shape `(batch_size, seq_length)`, *optional*):
  1195. Scale of the numeric values of every token. Can be obtained using [`AutoTokenizer`]. Only required in case
  1196. of weak supervision for aggregation (WTQ) to calculate the regression loss.
  1197. Returns:
  1198. Examples:
  1199. ```python
  1200. >>> from transformers import AutoTokenizer, TapasForQuestionAnswering
  1201. >>> import pandas as pd
  1202. >>> tokenizer = AutoTokenizer.from_pretrained("google/tapas-base-finetuned-wtq")
  1203. >>> model = TapasForQuestionAnswering.from_pretrained("google/tapas-base-finetuned-wtq")
  1204. >>> data = {
  1205. ... "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"],
  1206. ... "Age": ["56", "45", "59"],
  1207. ... "Number of movies": ["87", "53", "69"],
  1208. ... }
  1209. >>> table = pd.DataFrame.from_dict(data)
  1210. >>> queries = ["How many movies has George Clooney played in?", "How old is Brad Pitt?"]
  1211. >>> inputs = tokenizer(table=table, queries=queries, padding="max_length", return_tensors="tf")
  1212. >>> outputs = model(**inputs)
  1213. >>> logits = outputs.logits
  1214. >>> logits_aggregation = outputs.logits_aggregation
  1215. ```"""
  1216. outputs = self.tapas(
  1217. input_ids=input_ids,
  1218. attention_mask=attention_mask,
  1219. token_type_ids=token_type_ids,
  1220. position_ids=position_ids,
  1221. head_mask=head_mask,
  1222. inputs_embeds=inputs_embeds,
  1223. output_attentions=output_attentions,
  1224. output_hidden_states=output_hidden_states,
  1225. return_dict=return_dict,
  1226. training=training,
  1227. )
  1228. sequence_output = outputs[0]
  1229. pooled_output = outputs[1]
  1230. sequence_output = self.dropout(sequence_output)
  1231. if input_ids is not None:
  1232. input_shape = shape_list(input_ids)
  1233. else:
  1234. input_shape = shape_list(inputs_embeds)[:-1]
  1235. # Construct indices for the table.
  1236. if token_type_ids is None:
  1237. token_type_ids = tf.fill(input_shape + [len(self.config.type_vocab_sizes)], 0)
  1238. token_types = [
  1239. "segment_ids",
  1240. "column_ids",
  1241. "row_ids",
  1242. "prev_labels",
  1243. "column_ranks",
  1244. "inv_column_ranks",
  1245. "numeric_relations",
  1246. ]
  1247. row_ids = token_type_ids[:, :, token_types.index("row_ids")]
  1248. column_ids = token_type_ids[:, :, token_types.index("column_ids")]
  1249. # Construct indices for the table.
  1250. row_index = IndexMap(
  1251. indices=tf.minimum(tf.cast(row_ids, tf.int32), self.config.max_num_rows - 1),
  1252. num_segments=self.config.max_num_rows,
  1253. batch_dims=1,
  1254. )
  1255. col_index = IndexMap(
  1256. indices=tf.minimum(tf.cast(column_ids, tf.int32), self.config.max_num_columns - 1),
  1257. num_segments=self.config.max_num_columns,
  1258. batch_dims=1,
  1259. )
  1260. cell_index = ProductIndexMap(row_index, col_index)
  1261. # Masks.
  1262. input_shape = shape_list(input_ids) if input_ids is not None else shape_list(inputs_embeds)[:-1]
  1263. if attention_mask is None:
  1264. attention_mask = tf.ones(input_shape)
  1265. # Table cells only, without question tokens and table headers.
  1266. if table_mask is None:
  1267. table_mask = tf.where(row_ids > 0, tf.ones_like(row_ids), tf.zeros_like(row_ids))
  1268. # <float32>[batch_size, seq_length]
  1269. input_mask_float = tf.cast(attention_mask, tf.float32)
  1270. table_mask_float = tf.cast(table_mask, tf.float32)
  1271. # Mask for cells that exist in the table (i.e. that are not padding).
  1272. cell_mask, _ = reduce_mean(input_mask_float, cell_index)
  1273. # Compute logits per token. These are used to select individual cells.
  1274. logits = self.compute_token_logits(sequence_output)
  1275. # Compute logits per column. These are used to select a column.
  1276. column_logits = None
  1277. if self.config.select_one_column:
  1278. column_logits = self.compute_column_logits(
  1279. sequence_output, cell_index, cell_mask, self.config.allow_empty_column_selection
  1280. )
  1281. # Aggregate logits.
  1282. logits_aggregation = None
  1283. if self.config.num_aggregation_labels > 0:
  1284. logits_aggregation = self.aggregation_classifier(pooled_output)
  1285. # Total loss calculation
  1286. total_loss = tf.zeros(shape=(1,), dtype=tf.float32)
  1287. calculate_loss = False
  1288. if labels is not None:
  1289. calculate_loss = True
  1290. is_supervised = not self.config.num_aggregation_labels > 0 or not self.config.use_answer_as_supervision
  1291. # Semi-supervised cell selection in case of no aggregation:
  1292. # If the answer (the denotation) appears directly in the table we might
  1293. # select the answer without applying any aggregation function. There are
  1294. # some ambiguous cases, see utils._calculate_aggregate_mask for more info.
  1295. # `aggregate_mask` is 1 for examples where we chose to aggregate and 0
  1296. # for examples where we chose to select the answer directly.
  1297. # `labels` encodes the positions of the answer appearing in the table.
  1298. if is_supervised:
  1299. aggregate_mask = None
  1300. else:
  1301. if float_answer is not None:
  1302. assert (
  1303. shape_list(labels)[0] == shape_list(float_answer)[0]
  1304. ), "Make sure the answers are a FloatTensor of shape (batch_size,)"
  1305. # <float32>[batch_size]
  1306. aggregate_mask = _calculate_aggregate_mask(
  1307. float_answer,
  1308. pooled_output,
  1309. self.config.cell_selection_preference,
  1310. labels,
  1311. self.aggregation_classifier,
  1312. )
  1313. else:
  1314. aggregate_mask = None
  1315. raise ValueError("You have to specify float answers in order to calculate the aggregate mask")
  1316. # Cell selection log-likelihood
  1317. if self.config.average_logits_per_cell:
  1318. logits_per_cell, _ = reduce_mean(logits, cell_index)
  1319. logits = gather(logits_per_cell, cell_index)
  1320. dist_per_token = tfp.distributions.Bernoulli(logits=logits)
  1321. # Compute cell selection loss per example.
  1322. selection_loss_per_example = None
  1323. if not self.config.select_one_column:
  1324. weight = tf.where(
  1325. labels == 0,
  1326. tf.ones_like(labels, dtype=tf.float32),
  1327. self.config.positive_label_weight * tf.ones_like(labels, dtype=tf.float32),
  1328. )
  1329. selection_loss_per_token = -dist_per_token.log_prob(labels) * weight
  1330. selection_loss_per_example = tf.reduce_sum(selection_loss_per_token * input_mask_float, axis=1) / (
  1331. tf.reduce_sum(input_mask_float, axis=1) + EPSILON_ZERO_DIVISION
  1332. )
  1333. else:
  1334. selection_loss_per_example, logits = _single_column_cell_selection_loss(
  1335. logits, column_logits, labels, cell_index, col_index, cell_mask
  1336. )
  1337. dist_per_token = tfp.distributions.Bernoulli(logits=logits)
  1338. # Supervised cell selection
  1339. if self.config.disable_per_token_loss:
  1340. pass
  1341. elif is_supervised:
  1342. total_loss += tf.reduce_mean(selection_loss_per_example)
  1343. else:
  1344. # For the not supervised case, do not assign loss for cell selection
  1345. total_loss += tf.reduce_mean(selection_loss_per_example * (1.0 - aggregate_mask))
  1346. # Semi-supervised regression loss and supervised loss for aggregations
  1347. if self.config.num_aggregation_labels > 0:
  1348. if is_supervised:
  1349. # Note that `aggregate_mask` is None if the setting is supervised.
  1350. if aggregation_labels is not None:
  1351. assert (
  1352. shape_list(labels)[0] == shape_list(aggregation_labels)[0]
  1353. ), "Make sure the aggregation labels are a LongTensor of shape (batch_size,)"
  1354. per_example_additional_loss = _calculate_aggregation_loss(
  1355. logits_aggregation,
  1356. aggregate_mask,
  1357. aggregation_labels,
  1358. self.config.use_answer_as_supervision,
  1359. self.config.num_aggregation_labels,
  1360. self.config.aggregation_loss_weight,
  1361. )
  1362. else:
  1363. raise ValueError(
  1364. "You have to specify aggregation labels in order to calculate the aggregation loss"
  1365. )
  1366. else:
  1367. aggregation_labels = tf.zeros(shape_list(labels)[0], dtype=tf.int32)
  1368. per_example_additional_loss = _calculate_aggregation_loss(
  1369. logits_aggregation,
  1370. aggregate_mask,
  1371. aggregation_labels,
  1372. self.config.use_answer_as_supervision,
  1373. self.config.num_aggregation_labels,
  1374. self.config.aggregation_loss_weight,
  1375. )
  1376. if self.config.use_answer_as_supervision:
  1377. if numeric_values is not None and numeric_values_scale is not None:
  1378. assert shape_list(numeric_values) == shape_list(numeric_values_scale)
  1379. # Add regression loss for numeric answers which require aggregation.
  1380. answer_loss, large_answer_loss_mask = _calculate_regression_loss(
  1381. float_answer,
  1382. aggregate_mask,
  1383. dist_per_token,
  1384. numeric_values,
  1385. numeric_values_scale,
  1386. table_mask_float,
  1387. logits_aggregation,
  1388. self.config,
  1389. )
  1390. per_example_additional_loss += answer_loss
  1391. # Zero loss for examples with answer_loss > cutoff.
  1392. per_example_additional_loss *= large_answer_loss_mask
  1393. else:
  1394. raise ValueError(
  1395. "You have to specify numeric values and numeric values scale in order to calculate the"
  1396. " regression loss"
  1397. )
  1398. total_loss += tf.reduce_mean(per_example_additional_loss)
  1399. else:
  1400. # if no label ids are provided, set them to zeros in order to properly compute logits
  1401. labels = tf.zeros_like(logits)
  1402. _, logits = _single_column_cell_selection_loss(
  1403. logits, column_logits, labels, cell_index, col_index, cell_mask
  1404. )
  1405. if not return_dict:
  1406. output = (logits, logits_aggregation) + outputs[2:]
  1407. return ((total_loss,) + output) if calculate_loss else output
  1408. return TFTableQuestionAnsweringOutput(
  1409. loss=total_loss if calculate_loss else None,
  1410. logits=logits,
  1411. logits_aggregation=logits_aggregation,
  1412. hidden_states=outputs.hidden_states,
  1413. attentions=outputs.attentions,
  1414. )
  1415. def build(self, input_shape=None):
  1416. if self.built:
  1417. return
  1418. self.built = True
  1419. if getattr(self, "tapas", None) is not None:
  1420. with tf.name_scope(self.tapas.name):
  1421. self.tapas.build(None)
  1422. if getattr(self, "compute_token_logits", None) is not None:
  1423. with tf.name_scope(self.compute_token_logits.name):
  1424. self.compute_token_logits.build(None)
  1425. if getattr(self, "compute_column_logits", None) is not None:
  1426. with tf.name_scope(self.compute_column_logits.name):
  1427. self.compute_column_logits.build(None)
  1428. if getattr(self, "aggregation_classifier", None) is not None:
  1429. with tf.name_scope(self.aggregation_classifier.name):
  1430. self.aggregation_classifier.build([None, None, self.config.hidden_size])
  1431. @add_start_docstrings(
  1432. """
  1433. Tapas Model with a sequence classification head on top (a linear layer on top of the pooled output), e.g. for table
  1434. entailment tasks, such as TabFact (Chen et al., 2020).
  1435. """,
  1436. TAPAS_START_DOCSTRING,
  1437. )
  1438. class TFTapasForSequenceClassification(TFTapasPreTrainedModel, TFSequenceClassificationLoss):
  1439. def __init__(self, config: TapasConfig, *inputs, **kwargs):
  1440. super().__init__(config, *inputs, **kwargs)
  1441. self.num_labels = config.num_labels
  1442. self.tapas = TFTapasMainLayer(config, name="tapas")
  1443. self.dropout = keras.layers.Dropout(config.hidden_dropout_prob, name="dropout")
  1444. self.classifier = keras.layers.Dense(
  1445. config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
  1446. )
  1447. self.config = config
  1448. @unpack_inputs
  1449. @add_start_docstrings_to_model_forward(TAPAS_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
  1450. @replace_return_docstrings(output_type=TFSequenceClassifierOutput, config_class=_CONFIG_FOR_DOC)
  1451. def call(
  1452. self,
  1453. input_ids: TFModelInputType | None = None,
  1454. attention_mask: np.ndarray | tf.Tensor | None = None,
  1455. token_type_ids: np.ndarray | tf.Tensor | None = None,
  1456. position_ids: np.ndarray | tf.Tensor | None = None,
  1457. head_mask: np.ndarray | tf.Tensor | None = None,
  1458. inputs_embeds: np.ndarray | tf.Tensor | None = None,
  1459. output_attentions: Optional[bool] = None,
  1460. output_hidden_states: Optional[bool] = None,
  1461. return_dict: Optional[bool] = None,
  1462. labels: np.ndarray | tf.Tensor | None = None,
  1463. training: Optional[bool] = False,
  1464. ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:
  1465. r"""
  1466. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1467. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  1468. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  1469. `config.num_labels > 1` a classification loss is computed (Cross-Entropy). Note: this is called
  1470. "classification_class_index" in the original implementation.
  1471. Returns:
  1472. Examples:
  1473. ```python
  1474. >>> from transformers import AutoTokenizer, TapasForSequenceClassification
  1475. >>> import tensorflow as tf
  1476. >>> import pandas as pd
  1477. >>> tokenizer = AutoTokenizer.from_pretrained("google/tapas-base-finetuned-tabfact")
  1478. >>> model = TapasForSequenceClassification.from_pretrained("google/tapas-base-finetuned-tabfact")
  1479. >>> data = {
  1480. ... "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"],
  1481. ... "Age": ["56", "45", "59"],
  1482. ... "Number of movies": ["87", "53", "69"],
  1483. ... }
  1484. >>> table = pd.DataFrame.from_dict(data)
  1485. >>> queries = [
  1486. ... "There is only one actor who is 45 years old",
  1487. ... "There are 3 actors which played in more than 60 movies",
  1488. ... ]
  1489. >>> inputs = tokenizer(table=table, queries=queries, padding="max_length", return_tensors="tf")
  1490. >>> labels = tf.convert_to_tensor([1, 0]) # 1 means entailed, 0 means refuted
  1491. >>> outputs = model(**inputs, labels=labels)
  1492. >>> loss = outputs.loss
  1493. >>> logits = outputs.logits
  1494. ```"""
  1495. outputs = self.tapas(
  1496. input_ids=input_ids,
  1497. attention_mask=attention_mask,
  1498. token_type_ids=token_type_ids,
  1499. position_ids=position_ids,
  1500. head_mask=head_mask,
  1501. inputs_embeds=inputs_embeds,
  1502. output_attentions=output_attentions,
  1503. output_hidden_states=output_hidden_states,
  1504. return_dict=return_dict,
  1505. training=training,
  1506. )
  1507. pooled_output = outputs[1]
  1508. pooled_output = self.dropout(inputs=pooled_output, training=training)
  1509. logits = self.classifier(inputs=pooled_output)
  1510. loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=logits)
  1511. if not return_dict:
  1512. output = (logits,) + outputs[2:]
  1513. return ((loss,) + output) if loss is not None else output
  1514. return TFSequenceClassifierOutput(
  1515. loss=loss,
  1516. logits=logits,
  1517. hidden_states=outputs.hidden_states,
  1518. attentions=outputs.attentions,
  1519. )
  1520. def build(self, input_shape=None):
  1521. if self.built:
  1522. return
  1523. self.built = True
  1524. if getattr(self, "tapas", None) is not None:
  1525. with tf.name_scope(self.tapas.name):
  1526. self.tapas.build(None)
  1527. if getattr(self, "dropout", None) is not None:
  1528. with tf.name_scope(self.dropout.name):
  1529. self.dropout.build(None)
  1530. if getattr(self, "classifier", None) is not None:
  1531. with tf.name_scope(self.classifier.name):
  1532. self.classifier.build([None, None, self.config.hidden_size])
  1533. """ TAPAS utilities."""
  1534. class AverageApproximationFunction(str, enum.Enum):
  1535. RATIO = "ratio"
  1536. FIRST_ORDER = "first_order"
  1537. SECOND_ORDER = "second_order"
  1538. # Beginning of everything related to segmented tensors
  1539. class IndexMap:
  1540. """Index grouping entries within a tensor."""
  1541. def __init__(self, indices, num_segments, batch_dims=0):
  1542. """
  1543. Creates an index.
  1544. Args:
  1545. indices: <int32> Tensor of indices, same shape as `values`.
  1546. num_segments: <int32> Scalar tensor, the number of segments. All elements
  1547. in a batched segmented tensor must have the same number of segments (although many segments can be empty).
  1548. batch_dims: Python integer, the number of batch dimensions. The first
  1549. `batch_dims` dimensions of a SegmentedTensor are treated as batch dimensions. Segments in different batch
  1550. elements are always distinct even if they have the same index.
  1551. """
  1552. self.indices = tf.convert_to_tensor(indices)
  1553. self.num_segments = tf.convert_to_tensor(num_segments)
  1554. self.batch_dims = batch_dims
  1555. def batch_shape(self):
  1556. return tf.shape(self.indices)[: self.batch_dims]
  1557. class ProductIndexMap(IndexMap):
  1558. """The product of two indices."""
  1559. def __init__(self, outer_index, inner_index):
  1560. """
  1561. Combines indices i and j into pairs (i, j). The result is an index where each segment (i, j) is the
  1562. intersection of segments i and j. For example if the inputs represent table cells indexed by respectively rows
  1563. and columns the output will be a table indexed by (row, column) pairs, i.e. by cell. The implementation
  1564. combines indices {0, .., n - 1} and {0, .., m - 1} into {0, .., nm - 1}. The output has `num_segments` equal to
  1565. `outer_index.num_segements` * `inner_index.num_segments`.
  1566. Args:
  1567. outer_index: IndexMap.
  1568. inner_index: IndexMap, must have the same shape as `outer_index`.
  1569. """
  1570. if outer_index.batch_dims != inner_index.batch_dims:
  1571. raise ValueError("outer_index.batch_dims and inner_index.batch_dims must be the same.")
  1572. super(ProductIndexMap, self).__init__(
  1573. indices=(
  1574. inner_index.indices
  1575. + outer_index.indices * tf.cast(inner_index.num_segments, inner_index.indices.dtype)
  1576. ),
  1577. num_segments=inner_index.num_segments * outer_index.num_segments,
  1578. batch_dims=inner_index.batch_dims,
  1579. )
  1580. self.outer_index = outer_index
  1581. self.inner_index = inner_index
  1582. def project_outer(self, index):
  1583. """Projects an index with the same index set onto the outer components."""
  1584. return IndexMap(
  1585. indices=tf.math.floordiv(index.indices, self.inner_index.num_segments),
  1586. num_segments=self.outer_index.num_segments,
  1587. batch_dims=index.batch_dims,
  1588. )
  1589. def project_inner(self, index):
  1590. """Projects an index with the same index set onto the inner components."""
  1591. return IndexMap(
  1592. indices=tf.math.floormod(index.indices, self.inner_index.num_segments),
  1593. num_segments=self.inner_index.num_segments,
  1594. batch_dims=index.batch_dims,
  1595. )
  1596. def gather(values, index, name="segmented_gather"):
  1597. """
  1598. Gathers from `values` using the index map. For each element in the domain of the index map this operation looks up
  1599. a value for that index in `values`. Two elements from the same segment always get assigned the same value.
  1600. Args:
  1601. values: [B1, ..., Bn, num_segments, V1, ...] Tensor with segment values.
  1602. index: [B1, ..., Bn, I1, ..., Ik] IndexMap.
  1603. name: Name for the TensorFlow operation.
  1604. Returns:
  1605. [B1, ..., Bn, I1, ..., Ik, V1, ...] Tensor with the gathered values.
  1606. """
  1607. return tf.gather(values, index.indices, batch_dims=index.batch_dims, name=name)
  1608. def flatten(index, name="segmented_flatten"):
  1609. """
  1610. Flattens a batched index map to a 1d index map. This operation relabels the segments to keep batch elements
  1611. distinct. The k-th batch element will have indices shifted by `num_segments` * (k - 1). The result is a tensor with
  1612. `num_segments` multiplied by the number of elements in the batch.
  1613. Args:
  1614. index: IndexMap to flatten.
  1615. name: Name for the TensorFlow operation.
  1616. Returns:
  1617. The flattened IndexMap.
  1618. """
  1619. batch_size = tf.reduce_prod(index.batch_shape())
  1620. offset = tf.range(batch_size) * index.num_segments
  1621. offset = tf.reshape(offset, index.batch_shape())
  1622. for _ in range(index.batch_dims, index.indices.shape.rank):
  1623. offset = tf.expand_dims(offset, -1)
  1624. indices = tf.cast(offset, index.indices.dtype) + index.indices
  1625. return IndexMap(indices=tf.reshape(indices, [-1]), num_segments=index.num_segments * batch_size, batch_dims=0)
  1626. def range_index_map(batch_shape, num_segments, name="range_index_map"):
  1627. """
  1628. Constructs an index map equal to range(num_segments).
  1629. Args:
  1630. batch_shape (`tf.Tensor`):
  1631. Batch shape
  1632. num_segments (`int`):
  1633. Number of segments
  1634. name (`str`, *optional*, defaults to 'range_index_map'):
  1635. Name for the operation. Currently not used
  1636. Returns:
  1637. (`IndexMap`): IndexMap of shape batch_shape with elements equal to range(num_segments).
  1638. """
  1639. batch_shape = tf.convert_to_tensor(batch_shape)
  1640. batch_shape.shape.assert_has_rank(1)
  1641. num_segments = tf.convert_to_tensor(num_segments)
  1642. num_segments.shape.assert_has_rank(0)
  1643. indices = tf.range(num_segments)
  1644. shape = tf.concat([tf.ones_like(batch_shape, dtype=tf.int32), tf.expand_dims(num_segments, axis=0)], axis=0)
  1645. indices = tf.reshape(indices, shape)
  1646. multiples = tf.concat([batch_shape, [1]], axis=0)
  1647. indices = tf.tile(indices, multiples)
  1648. return IndexMap(indices=indices, num_segments=num_segments, batch_dims=batch_shape.shape.as_list()[0])
  1649. def _segment_reduce(values, index, segment_reduce_fn, name):
  1650. """
  1651. Applies a segment reduction segment-wise.
  1652. Args:
  1653. values (`tf.Tensor`):
  1654. Tensor with segment values.
  1655. index (`IndexMap`):
  1656. IndexMap.
  1657. segment_reduce_fn (`str`):
  1658. Name for the reduce operation. One of "sum", "mean", "max" or "min".
  1659. name (`str`):
  1660. Name for the operation. Currently not used
  1661. Returns:
  1662. (`IndexMap`): IndexMap of shape batch_shape with elements equal to range(num_segments).
  1663. """
  1664. # Flatten the batch dimensions, as segments ops do not support batching.
  1665. # However if `values` has extra dimensions to the right keep them
  1666. # unflattened. Segmented ops support vector-valued operations.
  1667. flat_index = flatten(index)
  1668. vector_shape = tf.shape(values)[index.indices.shape.rank :]
  1669. flattened_shape = tf.concat([[-1], vector_shape], axis=0)
  1670. flat_values = tf.reshape(values, flattened_shape)
  1671. segment_means = segment_reduce_fn(
  1672. data=flat_values, segment_ids=flat_index.indices, num_segments=flat_index.num_segments
  1673. )
  1674. # Unflatten the values.
  1675. new_shape = tf.concat([index.batch_shape(), [index.num_segments], vector_shape], axis=0)
  1676. output_values = tf.reshape(segment_means, new_shape)
  1677. output_index = range_index_map(index.batch_shape(), index.num_segments)
  1678. return output_values, output_index
  1679. def reduce_mean(values, index, name="segmented_reduce_mean"):
  1680. """
  1681. Averages a tensor over its segments. Outputs 0 for empty segments. This operations computes the mean over segments,
  1682. with support for:
  1683. - Batching using the first dimensions [B1, B2, ..., Bn]. Each element in a batch can have different indices.
  1684. - Vectorization using the last dimension [V1, V2, ...]. If they are present the output will be a mean of vectors
  1685. rather than scalars.
  1686. Only the middle dimensions [I1, ..., Ik] are reduced by the operation.
  1687. Args:
  1688. values: [B1, B2, ..., Bn, I1, .., Ik, V1, V2, ..] tensor of values to be
  1689. averaged.
  1690. index: IndexMap [B1, B2, ..., Bn, I1, .., Ik] index defining the segments.
  1691. name: Name for the TensorFlow ops.
  1692. Returns:
  1693. A pair (output_values, output_index) where `output_values` is a tensor of shape [B1, B2, ..., Bn, num_segments,
  1694. V1, V2, ..] and `index` is an IndexMap with shape [B1, B2, ..., Bn, num_segments].
  1695. """
  1696. return _segment_reduce(values, index, tf.math.unsorted_segment_mean, name)
  1697. def reduce_sum(values, index, name="segmented_reduce_sum"):
  1698. """
  1699. Sums a tensor over its segments. Outputs 0 for empty segments. This operations computes the sum over segments, with
  1700. support for:
  1701. - Batching using the first dimensions [B1, B2, ..., Bn]. Each element in a batch can have different indices.
  1702. - Vectorization using the last dimension [V1, V2, ...]. If they are present the output will be a sum of vectors
  1703. rather than scalars.
  1704. Only the middle dimensions [I1, ..., Ik] are reduced by the operation.
  1705. Args:
  1706. values: [B1, B2, ..., Bn, I1, .., Ik, V1, V2, ..] tensor of values to be
  1707. averaged.
  1708. index: IndexMap [B1, B2, ..., Bn, I1, .., Ik] index defining the segments.
  1709. name: Name for the TensorFlow ops.
  1710. Returns:
  1711. A pair (output_values, output_index) where `output_values` is a tensor of shape [B1, B2, ..., Bn, num_segments,
  1712. V1, V2, ..] and `index` is an IndexMap with shape [B1, B2, ..., Bn, num_segments].
  1713. """
  1714. return _segment_reduce(values, index, tf.math.unsorted_segment_sum, name)
  1715. def reduce_max(values, index, name="segmented_reduce_max"):
  1716. """
  1717. Computes the maximum over segments. This operations computes the maximum over segments, with support for:
  1718. - Batching using the first dimensions [B1, B2, ..., Bn]. Each element in a batch can have different indices.
  1719. - Vectorization using the last dimension [V1, V2, ...]. If they are present the output will be an element-wise
  1720. maximum of vectors rather than scalars.
  1721. Only the middle dimensions [I1, ..., Ik] are reduced by the operation.
  1722. Args:
  1723. values: [B1, B2, ..., Bn, I1, .., Ik, V1, V2, ..] tensor of values to be
  1724. averaged.
  1725. index: IndexMap [B1, B2, ..., Bn, I1, .., Ik] index defining the segments.
  1726. name: Name for the TensorFlow ops.
  1727. Returns:
  1728. A pair (output_values, output_index) where `output_values` is a tensor of shape [B1, B2, ..., Bn, num_segments,
  1729. V1, V2, ..] and `index` is an IndexMap with shape [B1, B2, ..., Bn, num_segments].
  1730. """
  1731. return _segment_reduce(values, index, tf.math.unsorted_segment_max, name)
  1732. def reduce_min(values, index, name="segmented_reduce_min"):
  1733. """Computes the minimum over segments."""
  1734. return _segment_reduce(values, index, tf.math.unsorted_segment_min, name)
  1735. def _single_column_cell_selection_loss(token_logits, column_logits, labels, cell_index, col_index, cell_mask):
  1736. """
  1737. Computes the loss for cell selection constrained to a single column. The loss is a hierarchical log-likelihood. The
  1738. model first predicts a column and then selects cells within that column (conditioned on the column). Cells outside
  1739. the selected column are never selected.
  1740. Args:
  1741. token_logits (`tf.Tensor` of shape `(batch_size, sequence_length)`):
  1742. Tensor containing the logits per token.
  1743. column_logits (`tf.Tensor` of shape `(batch_size, max_num_cols)`):
  1744. Tensor containing the logits per column.
  1745. labels (`tf.Tensor` of shape `(batch_size, sequence_length)`):
  1746. Labels per token.
  1747. cell_index (`ProductIndexMap`):
  1748. Index that groups tokens into cells.
  1749. col_index (`IndexMap`):
  1750. Index that groups tokens into columns.
  1751. cell_mask (`tf.Tensor` of shape `(batch_size, max_num_rows * max_num_cols)`):
  1752. Mask for cells that exist in the table (i.e. that are not padding).
  1753. Returns:
  1754. selection_loss_per_example (`tf.Tensor` of shape `(batch_size,)`): Loss for each example. logits (`tf.Tensor`
  1755. of shape `(batch_size, sequence_length)`): New logits which are only allowed to select cells in a single
  1756. column. Logits outside of the most likely column according to *column_logits* will be set to a very low value
  1757. (such that the probabilities are 0).
  1758. """
  1759. # First find the column we should select. We use the column with maximum
  1760. # number of selected cells.
  1761. labels_per_column, _ = reduce_sum(tf.cast(labels, tf.float32), col_index)
  1762. column_label = tf.argmax(labels_per_column, axis=-1, output_type=tf.int32)
  1763. # Check if there are no selected cells in the column. In that case the model
  1764. # should predict the special column id 0, which means "select nothing".
  1765. no_cell_selected = tf.equal(tf.reduce_max(labels_per_column, axis=-1), 0)
  1766. column_label = tf.where(no_cell_selected, tf.zeros_like(column_label), column_label)
  1767. column_dist = tfp.distributions.Categorical(logits=column_logits)
  1768. column_loss_per_example = -column_dist.log_prob(column_label)
  1769. # Reduce the labels and logits to per-cell from per-token.
  1770. logits_per_cell, _ = reduce_mean(token_logits, cell_index)
  1771. labels_per_cell, labels_index = reduce_max(tf.cast(labels, tf.int32), cell_index)
  1772. # Mask for the selected column.
  1773. column_id_for_cells = cell_index.project_inner(labels_index).indices
  1774. column_mask = tf.cast(tf.equal(column_id_for_cells, tf.expand_dims(column_label, axis=1)), tf.float32)
  1775. # Compute the log-likelihood for cells, but only for the selected column.
  1776. cell_dist = tfp.distributions.Bernoulli(logits=logits_per_cell)
  1777. cell_log_prob = cell_dist.log_prob(labels_per_cell)
  1778. cell_loss = -tf.reduce_sum(cell_log_prob * column_mask * cell_mask, axis=1)
  1779. # We need to normalize the loss by the number of cells in the column.
  1780. cell_loss /= tf.reduce_sum(column_mask * cell_mask, axis=1) + EPSILON_ZERO_DIVISION
  1781. selection_loss_per_example = column_loss_per_example
  1782. selection_loss_per_example += tf.where(no_cell_selected, tf.zeros_like(selection_loss_per_example), cell_loss)
  1783. # Set the probs outside the selected column (selected by the *model*)
  1784. # to 0. This ensures backwards compatibility with models that select
  1785. # cells from multiple columns.
  1786. selected_column_id = tf.argmax(column_logits, axis=-1, output_type=tf.int32)
  1787. selected_column_mask = tf.cast(
  1788. tf.equal(column_id_for_cells, tf.expand_dims(selected_column_id, axis=-1)), tf.float32
  1789. )
  1790. # Never select cells with the special column id 0.
  1791. selected_column_mask = tf.where(
  1792. tf.equal(column_id_for_cells, 0), tf.zeros_like(selected_column_mask), selected_column_mask
  1793. )
  1794. logits_per_cell += CLOSE_ENOUGH_TO_LOG_ZERO * (1.0 - cell_mask * selected_column_mask)
  1795. logits = gather(logits_per_cell, cell_index)
  1796. return selection_loss_per_example, logits
  1797. def _calculate_aggregate_mask(answer, pooled_output, cell_selection_preference, labels, aggregation_classifier):
  1798. """
  1799. Finds examples where the model should select cells with no aggregation.
  1800. Returns a mask that determines for which examples should the model select answers directly from the table, without
  1801. any aggregation function. If the answer is a piece of text the case is unambiguous as aggregation functions only
  1802. apply to numbers. If the answer is a number but does not appear in the table then we must use some aggregation
  1803. case. The ambiguous case is when the answer is a number that also appears in the table. In this case we use the
  1804. aggregation function probabilities predicted by the model to decide whether to select or aggregate. The threshold
  1805. for this is a hyperparameter *cell_selection_preference*
  1806. Args:
  1807. answer (`tf.Tensor` of shape `(batch_size, )`):
  1808. Answer for every example in the batch. Nan if there is no scalar answer.
  1809. pooled_output (`tf.Tensor` of shape `(batch_size, hidden_size)`):
  1810. Output of the pooler (BertPooler) on top of the encoder layer.
  1811. cell_selection_preference (`float`):
  1812. Preference for cell selection in ambiguous cases.
  1813. labels (`tf.Tensor` of shape `(batch_size, sequence_length)`):
  1814. Labels per token. aggregation_classifier (`torch.nn.Linear`): Aggregation head
  1815. Returns:
  1816. aggregate_mask (`tf.Tensor` of shape `(batch_size,)`): A mask set to 1 for examples that should use aggregation
  1817. functions.
  1818. """
  1819. # tf.Tensor(batch_size,)
  1820. aggregate_mask_init = tf.cast(tf.logical_not(tf.math.is_nan(answer)), tf.float32)
  1821. logits_aggregation = aggregation_classifier(pooled_output)
  1822. dist_aggregation = tfp.distributions.Categorical(logits=logits_aggregation)
  1823. # Index 0 corresponds to "no aggregation".
  1824. aggregation_ops_total_mass = tf.reduce_sum(dist_aggregation.probs_parameter()[:, 1:], axis=1)
  1825. # Cell selection examples according to current model.
  1826. is_pred_cell_selection = aggregation_ops_total_mass <= cell_selection_preference
  1827. # Examples with non-empty cell selection supervision.
  1828. is_cell_supervision_available = tf.reduce_sum(labels, axis=1) > 0
  1829. aggregate_mask = tf.where(
  1830. tf.logical_and(is_pred_cell_selection, is_cell_supervision_available),
  1831. tf.zeros_like(aggregate_mask_init, dtype=tf.float32),
  1832. aggregate_mask_init,
  1833. )
  1834. aggregate_mask = tf.stop_gradient(aggregate_mask)
  1835. return aggregate_mask
  1836. def _calculate_aggregation_loss_known(
  1837. logits_aggregation, aggregate_mask, aggregation_labels, use_answer_as_supervision, num_aggregation_labels
  1838. ):
  1839. """
  1840. Calculates aggregation loss when its type is known during training.
  1841. In the weakly supervised setting, the only known information is that for cell selection examples, "no aggregation"
  1842. should be predicted. For other examples (those that require aggregation), no loss is accumulated. In the setting
  1843. where aggregation type is always known, standard cross entropy loss is accumulated for all examples
  1844. Args:
  1845. logits_aggregation (`tf.Tensor` of shape `(batch_size, num_aggregation_labels)`):
  1846. Logits per aggregation operation.
  1847. aggregate_mask (`tf.Tensor` of shape `(batch_size, )`):
  1848. A mask set to 1 for examples that should use aggregation functions.
  1849. aggregation_labels (`tf.Tensor` of shape `(batch_size, )`):
  1850. Aggregation function id for every example in the batch.
  1851. use_answer_as_supervision (`bool`, *optional*):
  1852. Whether to use the answer as the only supervision for aggregation examples.
  1853. num_aggregation_labels (`int`, *optional*, defaults to 0):
  1854. The number of aggregation operators to predict.
  1855. Returns:
  1856. aggregation_loss_known (`tf.Tensor` of shape `(batch_size,)`): Aggregation loss (when its type is known during
  1857. training) per example.
  1858. """
  1859. if use_answer_as_supervision:
  1860. # Prepare "no aggregation" targets for cell selection examples.
  1861. target_aggregation = tf.zeros_like(aggregate_mask, dtype=tf.int32)
  1862. else:
  1863. # Use aggregation supervision as the target.
  1864. target_aggregation = aggregation_labels
  1865. one_hot_labels = tf.one_hot(target_aggregation, depth=num_aggregation_labels, dtype=tf.float32)
  1866. log_probs = tf.nn.log_softmax(logits_aggregation, axis=-1)
  1867. # <float32>[batch_size]
  1868. per_example_aggregation_intermediate = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
  1869. if use_answer_as_supervision:
  1870. # Accumulate loss only for examples requiring cell selection
  1871. # (no aggregation).
  1872. return per_example_aggregation_intermediate * (1 - aggregate_mask)
  1873. else:
  1874. return per_example_aggregation_intermediate
  1875. def _calculate_aggregation_loss_unknown(logits_aggregation, aggregate_mask):
  1876. """
  1877. Calculates aggregation loss in the case of answer supervision.
  1878. Args:
  1879. logits_aggregation (`tf.Tensor` of shape `(batch_size, num_aggregation_labels)`):
  1880. Logits per aggregation operation.
  1881. aggregate_mask (`tf.Tensor` of shape `(batch_size, )`):
  1882. A mask set to 1 for examples that should use aggregation functions
  1883. Returns:
  1884. aggregation_loss_unknown (`tf.Tensor` of shape `(batch_size,)`): Aggregation loss (in case of answer
  1885. supervision) per example.
  1886. """
  1887. dist_aggregation = tfp.distributions.Categorical(logits=logits_aggregation)
  1888. # Index 0 corresponds to "no aggregation".
  1889. aggregation_ops_total_mass = tf.reduce_sum(dist_aggregation.probs_parameter()[:, 1:], axis=1)
  1890. # Predict some aggregation in case of an answer that needs aggregation.
  1891. # This increases the probability of all aggregation functions, in a way
  1892. # similar to MML, but without considering whether the function gives the
  1893. # correct answer.
  1894. return -tf.math.log(aggregation_ops_total_mass) * aggregate_mask
  1895. def _calculate_aggregation_loss(
  1896. logits_aggregation,
  1897. aggregate_mask,
  1898. aggregation_labels,
  1899. use_answer_as_supervision,
  1900. num_aggregation_labels,
  1901. aggregation_loss_weight,
  1902. ):
  1903. """
  1904. Calculates the aggregation loss per example.
  1905. Args:
  1906. logits_aggregation (`tf.Tensor` of shape `(batch_size, num_aggregation_labels)`):
  1907. Logits per aggregation operation.
  1908. aggregate_mask (`tf.Tensor` of shape `(batch_size, )`):
  1909. A mask set to 1 for examples that should use aggregation functions.
  1910. aggregation_labels (`tf.Tensor` of shape `(batch_size, )`):
  1911. Aggregation function id for every example in the batch.
  1912. use_answer_as_supervision (`bool`, *optional*):
  1913. Whether to use the answer as the only supervision for aggregation examples.
  1914. num_aggregation_labels (`int`, *optional*, defaults to 0):
  1915. The number of aggregation operators to predict.
  1916. aggregation_loss_weight (`float`, *optional*, defaults to 1.0):
  1917. Importance weight for the aggregation loss.
  1918. Returns:
  1919. aggregation_loss (`tf.Tensor` of shape `(batch_size,)`): Aggregation loss per example.
  1920. """
  1921. per_example_aggregation_loss = _calculate_aggregation_loss_known(
  1922. logits_aggregation, aggregate_mask, aggregation_labels, use_answer_as_supervision, num_aggregation_labels
  1923. )
  1924. if use_answer_as_supervision:
  1925. # Add aggregation loss for numeric answers that need aggregation.
  1926. per_example_aggregation_loss += _calculate_aggregation_loss_unknown(logits_aggregation, aggregate_mask)
  1927. return aggregation_loss_weight * per_example_aggregation_loss
  1928. def _calculate_expected_result(
  1929. dist_per_cell, numeric_values, numeric_values_scale, input_mask_float, logits_aggregation, config
  1930. ):
  1931. """
  1932. Calculates the expected result given cell and aggregation probabilities.
  1933. Args:
  1934. dist_per_cell (`tfp.distributions.Bernoulli`):
  1935. Cell selection distribution for each cell.
  1936. numeric_values (`tf.Tensor` of shape `(batch_size, seq_length)`):
  1937. Numeric values of every token. Nan for tokens which are not numeric values.
  1938. numeric_values_scale (`tf.Tensor` of shape `(batch_size, seq_length)`):
  1939. Scale of the numeric values of every token.
  1940. input_mask_float (`tf.Tensor` of shape `(batch_size, seq_length)`):
  1941. Mask for the table, without question tokens and table headers.
  1942. logits_aggregation (`tf.Tensor` of shape `(batch_size, num_aggregation_labels)`):
  1943. Logits per aggregation operation.
  1944. config ([`TapasConfig`]):
  1945. Model configuration class with all the hyperparameters of the model
  1946. Returns:
  1947. expected_result (`tf.Tensor` of shape `(batch_size,)`): The expected result per example.
  1948. """
  1949. if config.use_gumbel_for_cells:
  1950. gumbel_dist = tfp.distributions.RelaxedBernoulli(
  1951. # The token logits where already divided by the temperature and used for
  1952. # computing cell selection errors so we need to multiply it again here
  1953. config.temperature,
  1954. logits=dist_per_cell.logits_parameter() * config.temperature,
  1955. )
  1956. scaled_probability_per_cell = gumbel_dist.sample()
  1957. else:
  1958. scaled_probability_per_cell = dist_per_cell.probs_parameter()
  1959. # <float32>[batch_size, seq_length]
  1960. scaled_probability_per_cell = (scaled_probability_per_cell / numeric_values_scale) * input_mask_float
  1961. count_result = tf.reduce_sum(scaled_probability_per_cell, axis=1)
  1962. numeric_values_masked = tf.where(
  1963. tf.math.is_nan(numeric_values), tf.zeros_like(numeric_values), numeric_values
  1964. ) # Mask non-numeric table values to zero.
  1965. sum_result = tf.reduce_sum(scaled_probability_per_cell * numeric_values_masked, axis=1)
  1966. avg_approximation = config.average_approximation_function
  1967. if avg_approximation == AverageApproximationFunction.RATIO:
  1968. average_result = sum_result / (count_result + EPSILON_ZERO_DIVISION)
  1969. elif avg_approximation == AverageApproximationFunction.FIRST_ORDER:
  1970. # The sum of all probabilities exept that correspond to other cells
  1971. ex = tf.reduce_sum(scaled_probability_per_cell, axis=1, keepdims=True) - scaled_probability_per_cell + 1
  1972. average_result = tf.reduce_sum(numeric_values_masked * scaled_probability_per_cell / ex, axis=1)
  1973. elif avg_approximation == AverageApproximationFunction.SECOND_ORDER:
  1974. # The sum of all probabilities exept that correspond to other cells
  1975. ex = tf.reduce_sum(scaled_probability_per_cell, axis=1, keepdims=True) - scaled_probability_per_cell + 1
  1976. pointwise_var = scaled_probability_per_cell * (1 - scaled_probability_per_cell)
  1977. var = tf.reduce_sum(pointwise_var, axis=1, keepdims=True) - pointwise_var
  1978. multiplier = (var / tf.math.square(ex) + 1) / ex
  1979. average_result = tf.reduce_sum(numeric_values_masked * scaled_probability_per_cell * multiplier, axis=1)
  1980. else:
  1981. raise ValueError("Invalid average_approximation_function: %s", config.average_approximation_function)
  1982. if config.use_gumbel_for_aggregation:
  1983. gumbel_dist = tfp.distributions.RelaxedOneHotCategorical(
  1984. config.aggregation_temperature, logits=logits_aggregation[:, 1:]
  1985. )
  1986. # <float32>[batch_size, num_aggregation_labels - 1]
  1987. aggregation_op_only_probs = gumbel_dist.sample()
  1988. else:
  1989. # <float32>[batch_size, num_aggregation_labels - 1]
  1990. aggregation_op_only_probs = stable_softmax(logits_aggregation[:, 1:] / config.aggregation_temperature, axis=-1)
  1991. all_results = tf.concat(
  1992. [
  1993. tf.expand_dims(sum_result, axis=1),
  1994. tf.expand_dims(average_result, axis=1),
  1995. tf.expand_dims(count_result, axis=1),
  1996. ],
  1997. axis=1,
  1998. )
  1999. expected_result = tf.reduce_sum(all_results * aggregation_op_only_probs, axis=1)
  2000. return expected_result
  2001. def _calculate_regression_loss(
  2002. answer,
  2003. aggregate_mask,
  2004. dist_per_cell,
  2005. numeric_values,
  2006. numeric_values_scale,
  2007. input_mask_float,
  2008. logits_aggregation,
  2009. config,
  2010. ):
  2011. """
  2012. Calculates the regression loss per example.
  2013. Args:
  2014. answer (`tf.Tensor` of shape `(batch_size,)`):
  2015. Answer for every example in the batch. Nan if there is no scalar answer.
  2016. aggregate_mask (`tf.Tensor` of shape `(batch_size,)`):
  2017. A mask set to 1 for examples that should use aggregation functions.
  2018. dist_per_cell (`torch.distributions.Bernoulli`):
  2019. Cell selection distribution for each cell.
  2020. numeric_values (`tf.Tensor` of shape `(batch_size, seq_length)`):
  2021. Numeric values of every token. Nan for tokens which are not numeric values.
  2022. numeric_values_scale (`tf.Tensor` of shape `(batch_size, seq_length)`):
  2023. Scale of the numeric values of every token.
  2024. input_mask_float (`tf.Tensor` of shape `(batch_size, seq_length)`):
  2025. Mask for the table, without question tokens and table headers.
  2026. logits_aggregation (`tf.Tensor` of shape `(batch_size, num_aggregation_labels)`):
  2027. Logits per aggregation operation.
  2028. config ([`TapasConfig`]):
  2029. Model configuration class with all the parameters of the model
  2030. Returns:
  2031. per_example_answer_loss_scaled (`tf.Tensor` of shape `(batch_size,)`): Scales answer loss for each example in
  2032. the batch. large_answer_loss_mask (`tf.Tensor` of shape `(batch_size,)`): A mask which is 1 for examples for
  2033. which their answer loss is larger than the answer_loss_cutoff.
  2034. """
  2035. # float32 (batch_size,)
  2036. expected_result = _calculate_expected_result(
  2037. dist_per_cell, numeric_values, numeric_values_scale, input_mask_float, logits_aggregation, config
  2038. )
  2039. # <float32>[batch_size]
  2040. answer_masked = tf.where(tf.math.is_nan(answer), tf.zeros_like(answer), answer)
  2041. if config.use_normalized_answer_loss:
  2042. normalizer = tf.stop_gradient(
  2043. tf.math.maximum(tf.math.abs(expected_result), tf.math.abs(answer_masked)) + EPSILON_ZERO_DIVISION
  2044. )
  2045. normalized_answer_masked = answer_masked / normalizer
  2046. normalized_expected_result = expected_result / normalizer
  2047. per_example_answer_loss = tf.compat.v1.losses.huber_loss(
  2048. normalized_answer_masked * aggregate_mask,
  2049. normalized_expected_result * aggregate_mask,
  2050. delta=tf.cast(1.0, tf.float32),
  2051. reduction=tf.losses.Reduction.NONE,
  2052. )
  2053. else:
  2054. per_example_answer_loss = tf.compat.v1.losses.huber_loss(
  2055. answer_masked * aggregate_mask,
  2056. expected_result * aggregate_mask,
  2057. delta=tf.cast(config.huber_loss_delta, tf.float32),
  2058. reduction=tf.losses.Reduction.NONE,
  2059. )
  2060. if config.answer_loss_cutoff is None:
  2061. large_answer_loss_mask = tf.ones_like(per_example_answer_loss, dtype=tf.float32)
  2062. else:
  2063. large_answer_loss_mask = tf.where(
  2064. per_example_answer_loss > config.answer_loss_cutoff,
  2065. tf.zeros_like(per_example_answer_loss, dtype=tf.float32),
  2066. tf.ones_like(per_example_answer_loss, dtype=tf.float32),
  2067. )
  2068. per_example_answer_loss_scaled = config.answer_loss_importance * (per_example_answer_loss * aggregate_mask)
  2069. return per_example_answer_loss_scaled, large_answer_loss_mask