modeling_tapas.py 106 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347
  1. # coding=utf-8
  2. # Copyright 2020 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. """PyTorch TAPAS model."""
  16. import enum
  17. import math
  18. import os
  19. from dataclasses import dataclass
  20. from typing import Optional, Union
  21. import torch
  22. from torch import nn
  23. from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
  24. from ...activations import ACT2FN
  25. from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
  26. from ...modeling_layers import GradientCheckpointingLayer
  27. from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, MaskedLMOutput, SequenceClassifierOutput
  28. from ...modeling_utils import PreTrainedModel
  29. from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
  30. from ...utils import ModelOutput, auto_docstring, logging
  31. from ...utils.deprecation import deprecate_kwarg
  32. from .configuration_tapas import TapasConfig
  33. logger = logging.get_logger(__name__)
  34. EPSILON_ZERO_DIVISION = 1e-10
  35. CLOSE_ENOUGH_TO_LOG_ZERO = -10000.0
  36. @dataclass
  37. @auto_docstring(
  38. custom_intro="""
  39. Output type of [`TapasForQuestionAnswering`].
  40. """
  41. )
  42. class TableQuestionAnsweringOutput(ModelOutput):
  43. r"""
  44. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` (and possibly `answer`, `aggregation_labels`, `numeric_values` and `numeric_values_scale` are provided)):
  45. Total loss as the sum of the hierarchical cell selection log-likelihood loss and (optionally) the
  46. semi-supervised regression loss and (optionally) supervised loss for aggregations.
  47. logits (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
  48. Prediction scores of the cell selection head, for every token.
  49. logits_aggregation (`torch.FloatTensor`, *optional*, of shape `(batch_size, num_aggregation_labels)`):
  50. Prediction scores of the aggregation head, for every aggregation operator.
  51. """
  52. loss: Optional[torch.FloatTensor] = None
  53. logits: Optional[torch.FloatTensor] = None
  54. logits_aggregation: Optional[torch.FloatTensor] = None
  55. hidden_states: Optional[tuple[torch.FloatTensor]] = None
  56. attentions: Optional[tuple[torch.FloatTensor]] = None
  57. def load_tf_weights_in_tapas(model, config, tf_checkpoint_path):
  58. """
  59. Load tf checkpoints in a PyTorch model. This is an adaptation from load_tf_weights_in_bert
  60. - add cell selection and aggregation heads
  61. - take into account additional token type embedding layers
  62. """
  63. try:
  64. import re
  65. import numpy as np
  66. import tensorflow as tf
  67. except ImportError:
  68. logger.error(
  69. "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
  70. "https://www.tensorflow.org/install/ for installation instructions."
  71. )
  72. raise
  73. tf_path = os.path.abspath(tf_checkpoint_path)
  74. logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
  75. # Load weights from TF model
  76. init_vars = tf.train.list_variables(tf_path)
  77. names = []
  78. arrays = []
  79. for name, shape in init_vars:
  80. logger.info(f"Loading TF weight {name} with shape {shape}")
  81. array = tf.train.load_variable(tf_path, name)
  82. names.append(name)
  83. arrays.append(array)
  84. for name, array in zip(names, arrays):
  85. name = name.split("/")
  86. # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculate m and v
  87. # which are not required for using pretrained model
  88. if any(
  89. n
  90. in [
  91. "adam_v",
  92. "adam_m",
  93. "AdamWeightDecayOptimizer",
  94. "AdamWeightDecayOptimizer_1",
  95. "global_step",
  96. "seq_relationship",
  97. ]
  98. for n in name
  99. ):
  100. logger.info(f"Skipping {'/'.join(name)}")
  101. continue
  102. # in case the model is TapasForSequenceClassification, we skip output_bias and output_weights
  103. # since these are not used for classification
  104. if isinstance(model, TapasForSequenceClassification):
  105. if any(n in ["output_bias", "output_weights"] for n in name):
  106. logger.info(f"Skipping {'/'.join(name)}")
  107. continue
  108. # in case the model is TapasModel, we skip output_bias, output_weights, output_bias_cls and output_weights_cls
  109. # since this model does not have MLM and NSP heads
  110. if isinstance(model, TapasModel):
  111. if any(n in ["output_bias", "output_weights", "output_bias_cls", "output_weights_cls"] for n in name):
  112. logger.info(f"Skipping {'/'.join(name)}")
  113. continue
  114. # in case the model is TapasForMaskedLM, we skip the pooler
  115. if isinstance(model, TapasForMaskedLM):
  116. if any(n in ["pooler"] for n in name):
  117. logger.info(f"Skipping {'/'.join(name)}")
  118. continue
  119. # if first scope name starts with "bert", change it to "tapas"
  120. if name[0] == "bert":
  121. name[0] = "tapas"
  122. pointer = model
  123. for m_name in name:
  124. if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
  125. scope_names = re.split(r"_(\d+)", m_name)
  126. else:
  127. scope_names = [m_name]
  128. if scope_names[0] == "kernel" or scope_names[0] == "gamma":
  129. pointer = getattr(pointer, "weight")
  130. elif scope_names[0] == "beta":
  131. pointer = getattr(pointer, "bias")
  132. # cell selection heads
  133. elif scope_names[0] == "output_bias":
  134. if not isinstance(model, TapasForMaskedLM):
  135. pointer = getattr(pointer, "output_bias")
  136. else:
  137. pointer = getattr(pointer, "bias")
  138. elif scope_names[0] == "output_weights":
  139. pointer = getattr(pointer, "output_weights")
  140. elif scope_names[0] == "column_output_bias":
  141. pointer = getattr(pointer, "column_output_bias")
  142. elif scope_names[0] == "column_output_weights":
  143. pointer = getattr(pointer, "column_output_weights")
  144. # aggregation head
  145. elif scope_names[0] == "output_bias_agg":
  146. pointer = getattr(pointer, "aggregation_classifier")
  147. pointer = getattr(pointer, "bias")
  148. elif scope_names[0] == "output_weights_agg":
  149. pointer = getattr(pointer, "aggregation_classifier")
  150. pointer = getattr(pointer, "weight")
  151. # classification head
  152. elif scope_names[0] == "output_bias_cls":
  153. pointer = getattr(pointer, "classifier")
  154. pointer = getattr(pointer, "bias")
  155. elif scope_names[0] == "output_weights_cls":
  156. pointer = getattr(pointer, "classifier")
  157. pointer = getattr(pointer, "weight")
  158. else:
  159. try:
  160. pointer = getattr(pointer, scope_names[0])
  161. except AttributeError:
  162. logger.info(f"Skipping {'/'.join(name)}")
  163. continue
  164. if len(scope_names) >= 2:
  165. num = int(scope_names[1])
  166. pointer = pointer[num]
  167. if m_name[-11:] == "_embeddings":
  168. pointer = getattr(pointer, "weight")
  169. elif m_name[-13:] in [f"_embeddings_{i}" for i in range(7)]:
  170. pointer = getattr(pointer, "weight")
  171. elif m_name == "kernel":
  172. array = np.transpose(array)
  173. try:
  174. if pointer.shape != array.shape:
  175. raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
  176. except AssertionError as e:
  177. e.args += (pointer.shape, array.shape)
  178. raise
  179. logger.info(f"Initialize PyTorch weight {name}")
  180. # Added a check to see whether the array is a scalar (because bias terms in Tapas checkpoints can be
  181. # scalar => should first be converted to numpy arrays)
  182. if np.isscalar(array):
  183. array = np.array(array)
  184. pointer.data = torch.from_numpy(array)
  185. return model
  186. class TapasEmbeddings(nn.Module):
  187. """
  188. Construct the embeddings from word, position and token_type embeddings. Same as BertEmbeddings but with a number of
  189. additional token type embeddings to encode tabular structure.
  190. """
  191. def __init__(self, config):
  192. super().__init__()
  193. # we do not include config.disabled_features and config.disable_position_embeddings from the original implementation
  194. # word embeddings
  195. self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
  196. # position embeddings
  197. self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
  198. # token type embeddings
  199. for i, type_vocab_sizes in enumerate(config.type_vocab_sizes):
  200. name = f"token_type_embeddings_{i}"
  201. setattr(self, name, nn.Embedding(type_vocab_sizes, config.hidden_size))
  202. self.number_of_token_type_embeddings = len(config.type_vocab_sizes)
  203. # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
  204. # any TensorFlow checkpoint file
  205. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  206. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  207. self.config = config
  208. def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):
  209. if input_ids is not None:
  210. input_shape = input_ids.size()
  211. else:
  212. input_shape = inputs_embeds.size()[:-1]
  213. seq_length = input_shape[1]
  214. device = input_ids.device if input_ids is not None else inputs_embeds.device
  215. if position_ids is None:
  216. # create absolute position embeddings
  217. position_ids = torch.arange(seq_length, dtype=torch.long, device=device)
  218. position_ids = position_ids.unsqueeze(0).expand(input_shape)
  219. # when self.config.reset_position_index_per_cell is set to True, create relative position embeddings
  220. if self.config.reset_position_index_per_cell:
  221. # shape (batch_size, seq_len)
  222. col_index = IndexMap(token_type_ids[:, :, 1], self.config.type_vocab_sizes[1], batch_dims=1)
  223. # shape (batch_size, seq_len)
  224. row_index = IndexMap(token_type_ids[:, :, 2], self.config.type_vocab_sizes[2], batch_dims=1)
  225. # shape (batch_size, seq_len)
  226. full_index = ProductIndexMap(col_index, row_index)
  227. # shape (max_rows * max_columns,). First absolute position for every cell
  228. first_position_per_segment = reduce_min(position_ids, full_index)[0]
  229. # ? shape (batch_size, seq_len). First absolute position of the cell for every token
  230. first_position = gather(first_position_per_segment, full_index)
  231. # shape (1, seq_len)
  232. position = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0)
  233. position_ids = torch.min(
  234. torch.as_tensor(self.config.max_position_embeddings - 1, device=device), position - first_position
  235. )
  236. if token_type_ids is None:
  237. token_type_ids = torch.zeros(
  238. (input_shape + self.number_of_token_type_embeddings), dtype=torch.long, device=device
  239. )
  240. if inputs_embeds is None:
  241. inputs_embeds = self.word_embeddings(input_ids)
  242. position_embeddings = self.position_embeddings(position_ids)
  243. embeddings = inputs_embeds + position_embeddings
  244. for i in range(self.number_of_token_type_embeddings):
  245. name = f"token_type_embeddings_{i}"
  246. embeddings += getattr(self, name)(token_type_ids[:, :, i])
  247. embeddings = self.LayerNorm(embeddings)
  248. embeddings = self.dropout(embeddings)
  249. return embeddings
  250. class TapasSelfAttention(nn.Module):
  251. def __init__(self, config, layer_idx=None):
  252. super().__init__()
  253. if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
  254. raise ValueError(
  255. f"The hidden size {config.hidden_size} is not a multiple of the number of attention "
  256. f"heads {config.num_attention_heads}"
  257. )
  258. self.num_attention_heads = config.num_attention_heads
  259. self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
  260. self.all_head_size = self.num_attention_heads * self.attention_head_size
  261. self.query = nn.Linear(config.hidden_size, self.all_head_size)
  262. self.key = nn.Linear(config.hidden_size, self.all_head_size)
  263. self.value = nn.Linear(config.hidden_size, self.all_head_size)
  264. self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
  265. self.is_decoder = config.is_decoder
  266. self.layer_idx = layer_idx
  267. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  268. def forward(
  269. self,
  270. hidden_states,
  271. attention_mask=None,
  272. head_mask=None,
  273. encoder_hidden_states=None,
  274. past_key_values=None,
  275. output_attentions=False,
  276. cache_position=None,
  277. ):
  278. batch_size, seq_length, _ = hidden_states.shape
  279. query_layer = (
  280. self.query(hidden_states)
  281. .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
  282. .transpose(1, 2)
  283. )
  284. is_updated = False
  285. is_cross_attention = encoder_hidden_states is not None
  286. if past_key_values is not None:
  287. if isinstance(past_key_values, EncoderDecoderCache):
  288. is_updated = past_key_values.is_updated.get(self.layer_idx)
  289. if is_cross_attention:
  290. # after the first generated id, we can subsequently re-use all key/value_layer from cache
  291. curr_past_key_value = past_key_values.cross_attention_cache
  292. else:
  293. curr_past_key_value = past_key_values.self_attention_cache
  294. else:
  295. curr_past_key_value = past_key_values
  296. current_states = encoder_hidden_states if is_cross_attention else hidden_states
  297. if is_cross_attention and past_key_values is not None and is_updated:
  298. # reuse k,v, cross_attentions
  299. key_layer = curr_past_key_value.layers[self.layer_idx].keys
  300. value_layer = curr_past_key_value.layers[self.layer_idx].values
  301. else:
  302. key_layer = (
  303. self.key(current_states)
  304. .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
  305. .transpose(1, 2)
  306. )
  307. value_layer = (
  308. self.value(current_states)
  309. .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
  310. .transpose(1, 2)
  311. )
  312. if past_key_values is not None:
  313. # save all key/value_layer to cache to be re-used for fast auto-regressive generation
  314. cache_position = cache_position if not is_cross_attention else None
  315. key_layer, value_layer = curr_past_key_value.update(
  316. key_layer, value_layer, self.layer_idx, {"cache_position": cache_position}
  317. )
  318. # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
  319. if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
  320. past_key_values.is_updated[self.layer_idx] = True
  321. # Take the dot product between "query" and "key" to get the raw attention scores.
  322. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
  323. attention_scores = attention_scores / math.sqrt(self.attention_head_size)
  324. if attention_mask is not None:
  325. # Apply the attention mask is (precomputed for all layers in TapasModel forward() function)
  326. attention_scores = attention_scores + attention_mask
  327. # Normalize the attention scores to probabilities.
  328. attention_probs = nn.functional.softmax(attention_scores, dim=-1)
  329. # This is actually dropping out entire tokens to attend to, which might
  330. # seem a bit unusual, but is taken from the original Transformer paper.
  331. attention_probs = self.dropout(attention_probs)
  332. # Mask heads if we want to
  333. if head_mask is not None:
  334. attention_probs = attention_probs * head_mask
  335. context_layer = torch.matmul(attention_probs, value_layer)
  336. context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
  337. new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
  338. context_layer = context_layer.view(*new_context_layer_shape)
  339. outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
  340. if self.is_decoder:
  341. outputs = outputs + (past_key_values,)
  342. return outputs
  343. # Copied from transformers.models.bert.modeling_bert.BertSelfOutput
  344. class TapasSelfOutput(nn.Module):
  345. def __init__(self, config):
  346. super().__init__()
  347. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  348. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  349. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  350. def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
  351. hidden_states = self.dense(hidden_states)
  352. hidden_states = self.dropout(hidden_states)
  353. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  354. return hidden_states
  355. class TapasAttention(nn.Module):
  356. def __init__(self, config, layer_idx=None):
  357. super().__init__()
  358. self.self = TapasSelfAttention(config, layer_idx=layer_idx)
  359. self.output = TapasSelfOutput(config)
  360. self.pruned_heads = set()
  361. # Copied from transformers.models.bert.modeling_bert.BertAttention.prune_heads
  362. def prune_heads(self, heads):
  363. if len(heads) == 0:
  364. return
  365. heads, index = find_pruneable_heads_and_indices(
  366. heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
  367. )
  368. # Prune linear layers
  369. self.self.query = prune_linear_layer(self.self.query, index)
  370. self.self.key = prune_linear_layer(self.self.key, index)
  371. self.self.value = prune_linear_layer(self.self.value, index)
  372. self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
  373. # Update hyper params and store pruned heads
  374. self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
  375. self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
  376. self.pruned_heads = self.pruned_heads.union(heads)
  377. # Copied from transformers.models.bert.modeling_bert.BertAttention.forward
  378. def forward(
  379. self,
  380. hidden_states: torch.Tensor,
  381. attention_mask: Optional[torch.FloatTensor] = None,
  382. head_mask: Optional[torch.FloatTensor] = None,
  383. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  384. past_key_values: Optional[Cache] = None,
  385. output_attentions: Optional[bool] = False,
  386. cache_position: Optional[torch.Tensor] = None,
  387. ) -> tuple[torch.Tensor]:
  388. self_outputs = self.self(
  389. hidden_states,
  390. attention_mask=attention_mask,
  391. head_mask=head_mask,
  392. encoder_hidden_states=encoder_hidden_states,
  393. past_key_values=past_key_values,
  394. output_attentions=output_attentions,
  395. cache_position=cache_position,
  396. )
  397. attention_output = self.output(self_outputs[0], hidden_states)
  398. outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
  399. return outputs
  400. # Copied from transformers.models.bert.modeling_bert.BertIntermediate
  401. class TapasIntermediate(nn.Module):
  402. def __init__(self, config):
  403. super().__init__()
  404. self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
  405. if isinstance(config.hidden_act, str):
  406. self.intermediate_act_fn = ACT2FN[config.hidden_act]
  407. else:
  408. self.intermediate_act_fn = config.hidden_act
  409. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  410. hidden_states = self.dense(hidden_states)
  411. hidden_states = self.intermediate_act_fn(hidden_states)
  412. return hidden_states
  413. # Copied from transformers.models.bert.modeling_bert.BertOutput
  414. class TapasOutput(nn.Module):
  415. def __init__(self, config):
  416. super().__init__()
  417. self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
  418. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  419. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  420. def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
  421. hidden_states = self.dense(hidden_states)
  422. hidden_states = self.dropout(hidden_states)
  423. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  424. return hidden_states
  425. class TapasLayer(GradientCheckpointingLayer):
  426. def __init__(self, config, layer_idx=None):
  427. super().__init__()
  428. self.chunk_size_feed_forward = config.chunk_size_feed_forward
  429. self.seq_len_dim = 1
  430. self.attention = TapasAttention(config, layer_idx=layer_idx)
  431. self.is_decoder = config.is_decoder
  432. self.add_cross_attention = config.add_cross_attention
  433. if self.add_cross_attention:
  434. if not self.is_decoder:
  435. raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
  436. self.crossattention = TapasAttention(config, layer_idx=layer_idx)
  437. self.intermediate = TapasIntermediate(config)
  438. self.output = TapasOutput(config)
  439. # Copied from transformers.models.bert.modeling_bert.BertLayer.forward
  440. def forward(
  441. self,
  442. hidden_states: torch.Tensor,
  443. attention_mask: Optional[torch.FloatTensor] = None,
  444. head_mask: Optional[torch.FloatTensor] = None,
  445. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  446. encoder_attention_mask: Optional[torch.FloatTensor] = None,
  447. past_key_values: Optional[Cache] = None,
  448. output_attentions: Optional[bool] = False,
  449. cache_position: Optional[torch.Tensor] = None,
  450. ) -> tuple[torch.Tensor]:
  451. self_attention_outputs = self.attention(
  452. hidden_states,
  453. attention_mask=attention_mask,
  454. head_mask=head_mask,
  455. output_attentions=output_attentions,
  456. past_key_values=past_key_values,
  457. cache_position=cache_position,
  458. )
  459. attention_output = self_attention_outputs[0]
  460. outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
  461. if self.is_decoder and encoder_hidden_states is not None:
  462. if not hasattr(self, "crossattention"):
  463. raise ValueError(
  464. f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
  465. " by setting `config.add_cross_attention=True`"
  466. )
  467. cross_attention_outputs = self.crossattention(
  468. attention_output,
  469. attention_mask=encoder_attention_mask,
  470. head_mask=head_mask,
  471. encoder_hidden_states=encoder_hidden_states,
  472. past_key_values=past_key_values,
  473. output_attentions=output_attentions,
  474. cache_position=cache_position,
  475. )
  476. attention_output = cross_attention_outputs[0]
  477. outputs = outputs + cross_attention_outputs[1:] # add cross attentions if we output attention weights
  478. layer_output = apply_chunking_to_forward(
  479. self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
  480. )
  481. outputs = (layer_output,) + outputs
  482. return outputs
  483. # Copied from transformers.models.bert.modeling_bert.BertLayer.feed_forward_chunk
  484. def feed_forward_chunk(self, attention_output):
  485. intermediate_output = self.intermediate(attention_output)
  486. layer_output = self.output(intermediate_output, attention_output)
  487. return layer_output
  488. class TapasEncoder(nn.Module):
  489. def __init__(self, config):
  490. super().__init__()
  491. self.config = config
  492. self.layer = nn.ModuleList([TapasLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
  493. self.gradient_checkpointing = False
  494. def forward(
  495. self,
  496. hidden_states,
  497. attention_mask=None,
  498. head_mask=None,
  499. encoder_hidden_states=None,
  500. encoder_attention_mask=None,
  501. past_key_values=None,
  502. use_cache=None,
  503. output_attentions=False,
  504. output_hidden_states=False,
  505. return_dict=True,
  506. cache_position=None,
  507. ):
  508. if use_cache and past_key_values is None:
  509. past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
  510. if use_cache and isinstance(past_key_values, tuple):
  511. logger.warning_once(
  512. "Passing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.58.0. "
  513. "You should pass an instance of `EncoderDecoderCache` instead, e.g. "
  514. "`past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`."
  515. )
  516. past_key_values = EncoderDecoderCache.from_legacy_cache(past_key_values)
  517. all_hidden_states = () if output_hidden_states else None
  518. all_attentions = () if output_attentions else None
  519. for i, layer_module in enumerate(self.layer):
  520. if output_hidden_states:
  521. all_hidden_states = all_hidden_states + (hidden_states,)
  522. layer_head_mask = head_mask[i] if head_mask is not None else None
  523. layer_outputs = layer_module(
  524. hidden_states,
  525. attention_mask,
  526. layer_head_mask,
  527. encoder_hidden_states, # as a positional argument for gradient checkpointing
  528. encoder_attention_mask=encoder_attention_mask,
  529. past_key_values=past_key_values,
  530. output_attentions=output_attentions,
  531. cache_position=cache_position,
  532. )
  533. hidden_states = layer_outputs[0]
  534. if output_attentions:
  535. all_attentions = all_attentions + (layer_outputs[1],)
  536. if output_hidden_states:
  537. all_hidden_states = all_hidden_states + (hidden_states,)
  538. if not return_dict:
  539. return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
  540. return BaseModelOutput(
  541. last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
  542. )
  543. # Copied from transformers.models.bert.modeling_bert.BertPooler
  544. class TapasPooler(nn.Module):
  545. def __init__(self, config):
  546. super().__init__()
  547. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  548. self.activation = nn.Tanh()
  549. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  550. # We "pool" the model by simply taking the hidden state corresponding
  551. # to the first token.
  552. first_token_tensor = hidden_states[:, 0]
  553. pooled_output = self.dense(first_token_tensor)
  554. pooled_output = self.activation(pooled_output)
  555. return pooled_output
  556. # Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->Tapas
  557. class TapasPredictionHeadTransform(nn.Module):
  558. def __init__(self, config):
  559. super().__init__()
  560. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  561. if isinstance(config.hidden_act, str):
  562. self.transform_act_fn = ACT2FN[config.hidden_act]
  563. else:
  564. self.transform_act_fn = config.hidden_act
  565. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  566. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  567. hidden_states = self.dense(hidden_states)
  568. hidden_states = self.transform_act_fn(hidden_states)
  569. hidden_states = self.LayerNorm(hidden_states)
  570. return hidden_states
  571. # Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->Tapas
  572. class TapasLMPredictionHead(nn.Module):
  573. def __init__(self, config):
  574. super().__init__()
  575. self.transform = TapasPredictionHeadTransform(config)
  576. # The output weights are the same as the input embeddings, but there is
  577. # an output-only bias for each token.
  578. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  579. self.bias = nn.Parameter(torch.zeros(config.vocab_size))
  580. # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
  581. self.decoder.bias = self.bias
  582. def _tie_weights(self):
  583. self.decoder.bias = self.bias
  584. def forward(self, hidden_states):
  585. hidden_states = self.transform(hidden_states)
  586. hidden_states = self.decoder(hidden_states)
  587. return hidden_states
  588. # Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->Tapas
  589. class TapasOnlyMLMHead(nn.Module):
  590. def __init__(self, config):
  591. super().__init__()
  592. self.predictions = TapasLMPredictionHead(config)
  593. def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
  594. prediction_scores = self.predictions(sequence_output)
  595. return prediction_scores
  596. @auto_docstring
  597. class TapasPreTrainedModel(PreTrainedModel):
  598. config: TapasConfig
  599. base_model_prefix = "tapas"
  600. supports_gradient_checkpointing = True
  601. _supports_param_buffer_assignment = False
  602. # Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights with Bert->Tapas
  603. def _init_weights(self, module):
  604. """Initialize the weights"""
  605. if isinstance(module, nn.Linear):
  606. # Slightly different from the TF version which uses truncated_normal for initialization
  607. # cf https://github.com/pytorch/pytorch/pull/5617
  608. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  609. if module.bias is not None:
  610. module.bias.data.zero_()
  611. elif isinstance(module, nn.Embedding):
  612. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  613. if module.padding_idx is not None:
  614. module.weight.data[module.padding_idx].zero_()
  615. elif isinstance(module, nn.LayerNorm):
  616. module.bias.data.zero_()
  617. module.weight.data.fill_(1.0)
  618. elif isinstance(module, TapasLMPredictionHead):
  619. module.bias.data.zero_()
  620. @auto_docstring
  621. class TapasModel(TapasPreTrainedModel):
  622. """
  623. This class is a small change compared to [`BertModel`], taking into account the additional token type ids.
  624. The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
  625. cross-attention is added between the self-attention layers, following the architecture described in [Attention is
  626. all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
  627. Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
  628. """
  629. def __init__(self, config, add_pooling_layer=True):
  630. r"""
  631. add_pooling_layer (bool, *optional*, defaults to `True`):
  632. Whether to add a pooling layer
  633. """
  634. super().__init__(config)
  635. self.config = config
  636. self.embeddings = TapasEmbeddings(config)
  637. self.encoder = TapasEncoder(config)
  638. self.pooler = TapasPooler(config) if add_pooling_layer else None
  639. # Initialize weights and apply final processing
  640. self.post_init()
  641. def get_input_embeddings(self):
  642. return self.embeddings.word_embeddings
  643. def set_input_embeddings(self, value):
  644. self.embeddings.word_embeddings = value
  645. def _prune_heads(self, heads_to_prune):
  646. """
  647. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
  648. class PreTrainedModel
  649. """
  650. for layer, heads in heads_to_prune.items():
  651. self.encoder.layer[layer].attention.prune_heads(heads)
  652. @auto_docstring
  653. def forward(
  654. self,
  655. input_ids: Optional[torch.LongTensor] = None,
  656. attention_mask: Optional[torch.FloatTensor] = None,
  657. token_type_ids: Optional[torch.LongTensor] = None,
  658. position_ids: Optional[torch.LongTensor] = None,
  659. head_mask: Optional[torch.FloatTensor] = None,
  660. inputs_embeds: Optional[torch.FloatTensor] = None,
  661. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  662. encoder_attention_mask: Optional[torch.FloatTensor] = None,
  663. output_attentions: Optional[bool] = None,
  664. output_hidden_states: Optional[bool] = None,
  665. return_dict: Optional[bool] = None,
  666. ) -> Union[tuple, BaseModelOutputWithPooling]:
  667. r"""
  668. token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length, 7)`, *optional*):
  669. Token indices that encode tabular structure. Indices can be obtained using [`AutoTokenizer`]. See this
  670. class for more info.
  671. [What are token type IDs?](../glossary#token-type-ids)
  672. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  673. Indices of positions of each input sequence tokens in the position embeddings. If
  674. `reset_position_index_per_cell` of [`TapasConfig`] is set to `True`, relative position embeddings will be
  675. used. Selected in the range `[0, config.max_position_embeddings - 1]`.
  676. [What are position IDs?](../glossary#position-ids)
  677. Examples:
  678. ```python
  679. >>> from transformers import AutoTokenizer, TapasModel
  680. >>> import pandas as pd
  681. >>> tokenizer = AutoTokenizer.from_pretrained("google/tapas-base")
  682. >>> model = TapasModel.from_pretrained("google/tapas-base")
  683. >>> data = {
  684. ... "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"],
  685. ... "Age": ["56", "45", "59"],
  686. ... "Number of movies": ["87", "53", "69"],
  687. ... }
  688. >>> table = pd.DataFrame.from_dict(data)
  689. >>> queries = ["How many movies has George Clooney played in?", "How old is Brad Pitt?"]
  690. >>> inputs = tokenizer(table=table, queries=queries, padding="max_length", return_tensors="pt")
  691. >>> outputs = model(**inputs)
  692. >>> last_hidden_states = outputs.last_hidden_state
  693. ```"""
  694. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  695. output_hidden_states = (
  696. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  697. )
  698. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  699. if input_ids is not None and inputs_embeds is not None:
  700. raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
  701. elif input_ids is not None:
  702. self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
  703. input_shape = input_ids.size()
  704. elif inputs_embeds is not None:
  705. input_shape = inputs_embeds.size()[:-1]
  706. else:
  707. raise ValueError("You have to specify either input_ids or inputs_embeds")
  708. device = input_ids.device if input_ids is not None else inputs_embeds.device
  709. if attention_mask is None:
  710. attention_mask = torch.ones(input_shape, device=device)
  711. if token_type_ids is None:
  712. token_type_ids = torch.zeros(
  713. (*input_shape, len(self.config.type_vocab_sizes)), dtype=torch.long, device=device
  714. )
  715. # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
  716. # ourselves in which case we just need to make it broadcastable to all heads.
  717. extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
  718. # If a 2D ou 3D attention mask is provided for the cross-attention
  719. # we need to make broadcastabe to [batch_size, num_heads, seq_length, seq_length]
  720. if self.config.is_decoder and encoder_hidden_states is not None:
  721. encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
  722. encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
  723. if encoder_attention_mask is None:
  724. encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
  725. encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
  726. else:
  727. encoder_extended_attention_mask = None
  728. # Prepare head mask if needed
  729. # 1.0 in head_mask indicate we keep the head
  730. # attention_probs has shape bsz x n_heads x N x N
  731. # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
  732. # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
  733. head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
  734. embedding_output = self.embeddings(
  735. input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds
  736. )
  737. encoder_outputs = self.encoder(
  738. embedding_output,
  739. attention_mask=extended_attention_mask,
  740. head_mask=head_mask,
  741. encoder_hidden_states=encoder_hidden_states,
  742. encoder_attention_mask=encoder_extended_attention_mask,
  743. output_attentions=output_attentions,
  744. output_hidden_states=output_hidden_states,
  745. return_dict=return_dict,
  746. )
  747. sequence_output = encoder_outputs[0]
  748. pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
  749. if not return_dict:
  750. return (sequence_output, pooled_output) + encoder_outputs[1:]
  751. return BaseModelOutputWithPooling(
  752. last_hidden_state=sequence_output,
  753. pooler_output=pooled_output,
  754. hidden_states=encoder_outputs.hidden_states,
  755. attentions=encoder_outputs.attentions,
  756. )
  757. @auto_docstring
  758. class TapasForMaskedLM(TapasPreTrainedModel):
  759. _tied_weights_keys = ["cls.predictions.decoder.weight", "cls.predictions.decoder.bias"]
  760. config: TapasConfig
  761. base_model_prefix = "tapas"
  762. def __init__(self, config):
  763. super().__init__(config)
  764. self.tapas = TapasModel(config, add_pooling_layer=False)
  765. self.cls = TapasOnlyMLMHead(config)
  766. # Initialize weights and apply final processing
  767. self.post_init()
  768. def get_output_embeddings(self):
  769. return self.cls.predictions.decoder
  770. def set_output_embeddings(self, new_embeddings):
  771. self.cls.predictions.decoder = new_embeddings
  772. self.cls.predictions.bias = new_embeddings.bias
  773. @auto_docstring
  774. def forward(
  775. self,
  776. input_ids: Optional[torch.LongTensor] = None,
  777. attention_mask: Optional[torch.FloatTensor] = None,
  778. token_type_ids: Optional[torch.LongTensor] = None,
  779. position_ids: Optional[torch.LongTensor] = None,
  780. head_mask: Optional[torch.FloatTensor] = None,
  781. inputs_embeds: Optional[torch.FloatTensor] = None,
  782. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  783. encoder_attention_mask: Optional[torch.FloatTensor] = None,
  784. labels: Optional[torch.LongTensor] = None,
  785. output_attentions: Optional[bool] = None,
  786. output_hidden_states: Optional[bool] = None,
  787. return_dict: Optional[bool] = None,
  788. **kwargs,
  789. ) -> Union[tuple, MaskedLMOutput]:
  790. r"""
  791. token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length, 7)`, *optional*):
  792. Token indices that encode tabular structure. Indices can be obtained using [`AutoTokenizer`]. See this
  793. class for more info.
  794. [What are token type IDs?](../glossary#token-type-ids)
  795. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  796. Indices of positions of each input sequence tokens in the position embeddings. If
  797. `reset_position_index_per_cell` of [`TapasConfig`] is set to `True`, relative position embeddings will be
  798. used. Selected in the range `[0, config.max_position_embeddings - 1]`.
  799. [What are position IDs?](../glossary#position-ids)
  800. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  801. Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
  802. config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
  803. loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
  804. Examples:
  805. ```python
  806. >>> from transformers import AutoTokenizer, TapasForMaskedLM
  807. >>> import pandas as pd
  808. >>> tokenizer = AutoTokenizer.from_pretrained("google/tapas-base")
  809. >>> model = TapasForMaskedLM.from_pretrained("google/tapas-base")
  810. >>> data = {
  811. ... "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"],
  812. ... "Age": ["56", "45", "59"],
  813. ... "Number of movies": ["87", "53", "69"],
  814. ... }
  815. >>> table = pd.DataFrame.from_dict(data)
  816. >>> inputs = tokenizer(
  817. ... table=table, queries="How many [MASK] has George [MASK] played in?", return_tensors="pt"
  818. ... )
  819. >>> labels = tokenizer(
  820. ... table=table, queries="How many movies has George Clooney played in?", return_tensors="pt"
  821. ... )["input_ids"]
  822. >>> outputs = model(**inputs, labels=labels)
  823. >>> logits = outputs.logits
  824. ```"""
  825. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  826. outputs = self.tapas(
  827. input_ids,
  828. attention_mask=attention_mask,
  829. token_type_ids=token_type_ids,
  830. position_ids=position_ids,
  831. head_mask=head_mask,
  832. inputs_embeds=inputs_embeds,
  833. encoder_hidden_states=encoder_hidden_states,
  834. encoder_attention_mask=encoder_attention_mask,
  835. output_attentions=output_attentions,
  836. output_hidden_states=output_hidden_states,
  837. return_dict=return_dict,
  838. )
  839. sequence_output = outputs[0]
  840. prediction_scores = self.cls(sequence_output)
  841. masked_lm_loss = None
  842. if labels is not None:
  843. loss_fct = CrossEntropyLoss() # -100 index = padding token
  844. masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
  845. if not return_dict:
  846. output = (prediction_scores,) + outputs[2:]
  847. return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
  848. return MaskedLMOutput(
  849. loss=masked_lm_loss,
  850. logits=prediction_scores,
  851. hidden_states=outputs.hidden_states,
  852. attentions=outputs.attentions,
  853. )
  854. @auto_docstring(
  855. custom_intro="""
  856. Tapas Model with a cell selection head and optional aggregation head on top for question-answering tasks on tables
  857. (linear layers on top of the hidden-states output to compute `logits` and optional `logits_aggregation`), e.g. for
  858. SQA, WTQ or WikiSQL-supervised tasks.
  859. """
  860. )
  861. class TapasForQuestionAnswering(TapasPreTrainedModel):
  862. def __init__(self, config: TapasConfig):
  863. super().__init__(config)
  864. # base model
  865. self.tapas = TapasModel(config)
  866. # dropout (only used when training)
  867. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  868. # cell selection heads
  869. if config.init_cell_selection_weights_to_zero:
  870. # init_cell_selection_weights_to_zero: Whether the initial weights should be
  871. # set to 0. This ensures that all tokens have the same prior probability.
  872. self.output_weights = nn.Parameter(torch.zeros(config.hidden_size))
  873. self.column_output_weights = nn.Parameter(torch.zeros(config.hidden_size))
  874. else:
  875. self.output_weights = nn.Parameter(torch.empty(config.hidden_size))
  876. nn.init.normal_(
  877. self.output_weights, std=config.initializer_range
  878. ) # here, a truncated normal is used in the original implementation
  879. self.column_output_weights = nn.Parameter(torch.empty(config.hidden_size))
  880. nn.init.normal_(
  881. self.column_output_weights, std=config.initializer_range
  882. ) # here, a truncated normal is used in the original implementation
  883. self.output_bias = nn.Parameter(torch.zeros([]))
  884. self.column_output_bias = nn.Parameter(torch.zeros([]))
  885. # aggregation head
  886. if config.num_aggregation_labels > 0:
  887. self.aggregation_classifier = nn.Linear(config.hidden_size, config.num_aggregation_labels)
  888. # Initialize weights and apply final processing
  889. self.post_init()
  890. @auto_docstring
  891. def forward(
  892. self,
  893. input_ids: Optional[torch.LongTensor] = None,
  894. attention_mask: Optional[torch.FloatTensor] = None,
  895. token_type_ids: Optional[torch.LongTensor] = None,
  896. position_ids: Optional[torch.LongTensor] = None,
  897. head_mask: Optional[torch.FloatTensor] = None,
  898. inputs_embeds: Optional[torch.FloatTensor] = None,
  899. table_mask: Optional[torch.LongTensor] = None,
  900. labels: Optional[torch.LongTensor] = None,
  901. aggregation_labels: Optional[torch.LongTensor] = None,
  902. float_answer: Optional[torch.FloatTensor] = None,
  903. numeric_values: Optional[torch.FloatTensor] = None,
  904. numeric_values_scale: Optional[torch.FloatTensor] = None,
  905. output_attentions: Optional[bool] = None,
  906. output_hidden_states: Optional[bool] = None,
  907. return_dict: Optional[bool] = None,
  908. ) -> Union[tuple, TableQuestionAnsweringOutput]:
  909. r"""
  910. token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length, 7)`, *optional*):
  911. Token indices that encode tabular structure. Indices can be obtained using [`AutoTokenizer`]. See this
  912. class for more info.
  913. [What are token type IDs?](../glossary#token-type-ids)
  914. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  915. Indices of positions of each input sequence tokens in the position embeddings. If
  916. `reset_position_index_per_cell` of [`TapasConfig`] is set to `True`, relative position embeddings will be
  917. used. Selected in the range `[0, config.max_position_embeddings - 1]`.
  918. [What are position IDs?](../glossary#position-ids)
  919. table_mask (`torch.LongTensor` of shape `(batch_size, seq_length)`, *optional*):
  920. Mask for the table. Indicates which tokens belong to the table (1). Question tokens, table headers and
  921. padding are 0.
  922. labels (`torch.LongTensor` of shape `(batch_size, seq_length)`, *optional*):
  923. Labels per token for computing the hierarchical cell selection loss. This encodes the positions of the
  924. answer appearing in the table. Can be obtained using [`AutoTokenizer`].
  925. - 1 for tokens that are **part of the answer**,
  926. - 0 for tokens that are **not part of the answer**.
  927. aggregation_labels (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
  928. Aggregation function index for every example in the batch for computing the aggregation loss. Indices
  929. should be in `[0, ..., config.num_aggregation_labels - 1]`. Only required in case of strong supervision for
  930. aggregation (WikiSQL-supervised).
  931. float_answer (`torch.FloatTensor` of shape `(batch_size, )`, *optional*):
  932. Float answer for every example in the batch. Set to *float('nan')* for cell selection questions. Only
  933. required in case of weak supervision (WTQ) to calculate the aggregate mask and regression loss.
  934. numeric_values (`torch.FloatTensor` of shape `(batch_size, seq_length)`, *optional*):
  935. Numeric values of every token, NaN for tokens which are not numeric values. Can be obtained using
  936. [`AutoTokenizer`]. Only required in case of weak supervision for aggregation (WTQ) to calculate the
  937. regression loss.
  938. numeric_values_scale (`torch.FloatTensor` of shape `(batch_size, seq_length)`, *optional*):
  939. Scale of the numeric values of every token. Can be obtained using [`AutoTokenizer`]. Only required in case
  940. of weak supervision for aggregation (WTQ) to calculate the regression loss.
  941. Examples:
  942. ```python
  943. >>> from transformers import AutoTokenizer, TapasForQuestionAnswering
  944. >>> import pandas as pd
  945. >>> tokenizer = AutoTokenizer.from_pretrained("google/tapas-base-finetuned-wtq")
  946. >>> model = TapasForQuestionAnswering.from_pretrained("google/tapas-base-finetuned-wtq")
  947. >>> data = {
  948. ... "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"],
  949. ... "Age": ["56", "45", "59"],
  950. ... "Number of movies": ["87", "53", "69"],
  951. ... }
  952. >>> table = pd.DataFrame.from_dict(data)
  953. >>> queries = ["How many movies has George Clooney played in?", "How old is Brad Pitt?"]
  954. >>> inputs = tokenizer(table=table, queries=queries, padding="max_length", return_tensors="pt")
  955. >>> outputs = model(**inputs)
  956. >>> logits = outputs.logits
  957. >>> logits_aggregation = outputs.logits_aggregation
  958. ```"""
  959. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  960. outputs = self.tapas(
  961. input_ids,
  962. attention_mask=attention_mask,
  963. token_type_ids=token_type_ids,
  964. position_ids=position_ids,
  965. head_mask=head_mask,
  966. inputs_embeds=inputs_embeds,
  967. output_attentions=output_attentions,
  968. output_hidden_states=output_hidden_states,
  969. return_dict=return_dict,
  970. )
  971. sequence_output = outputs[0]
  972. pooled_output = outputs[1]
  973. sequence_output = self.dropout(sequence_output)
  974. if input_ids is not None:
  975. input_shape = input_ids.size()
  976. else:
  977. input_shape = inputs_embeds.size()[:-1]
  978. device = input_ids.device if input_ids is not None else inputs_embeds.device
  979. # Construct indices for the table.
  980. if token_type_ids is None:
  981. token_type_ids = torch.zeros(
  982. (*input_shape, len(self.config.type_vocab_sizes)), dtype=torch.long, device=device
  983. )
  984. token_types = [
  985. "segment_ids",
  986. "column_ids",
  987. "row_ids",
  988. "prev_labels",
  989. "column_ranks",
  990. "inv_column_ranks",
  991. "numeric_relations",
  992. ]
  993. row_ids = token_type_ids[:, :, token_types.index("row_ids")]
  994. column_ids = token_type_ids[:, :, token_types.index("column_ids")]
  995. row_index = IndexMap(
  996. indices=torch.min(row_ids, torch.as_tensor(self.config.max_num_rows - 1, device=row_ids.device)),
  997. num_segments=self.config.max_num_rows,
  998. batch_dims=1,
  999. )
  1000. col_index = IndexMap(
  1001. indices=torch.min(column_ids, torch.as_tensor(self.config.max_num_columns - 1, device=column_ids.device)),
  1002. num_segments=self.config.max_num_columns,
  1003. batch_dims=1,
  1004. )
  1005. cell_index = ProductIndexMap(row_index, col_index)
  1006. # Masks.
  1007. input_shape = input_ids.size() if input_ids is not None else inputs_embeds.size()[:-1]
  1008. device = input_ids.device if input_ids is not None else inputs_embeds.device
  1009. if attention_mask is None:
  1010. attention_mask = torch.ones(input_shape, device=device)
  1011. # Table cells only, without question tokens and table headers.
  1012. if table_mask is None:
  1013. table_mask = torch.where(row_ids > 0, torch.ones_like(row_ids), torch.zeros_like(row_ids))
  1014. # torch.FloatTensor[batch_size, seq_length]
  1015. input_mask_float = attention_mask.to(device=device, dtype=torch.float)
  1016. table_mask_float = table_mask.to(device=device, dtype=torch.float)
  1017. # Mask for cells that exist in the table (i.e. that are not padding).
  1018. cell_mask, _ = reduce_mean(input_mask_float, cell_index)
  1019. # Compute logits per token. These are used to select individual cells.
  1020. logits = compute_token_logits(sequence_output, self.config.temperature, self.output_weights, self.output_bias)
  1021. # Compute logits per column. These are used to select a column.
  1022. column_logits = None
  1023. if self.config.select_one_column:
  1024. column_logits = compute_column_logits(
  1025. sequence_output,
  1026. self.column_output_weights,
  1027. self.column_output_bias,
  1028. cell_index,
  1029. cell_mask,
  1030. self.config.allow_empty_column_selection,
  1031. )
  1032. # Aggregation logits
  1033. logits_aggregation = None
  1034. if self.config.num_aggregation_labels > 0:
  1035. logits_aggregation = self.aggregation_classifier(pooled_output)
  1036. # Total loss calculation
  1037. total_loss = 0.0
  1038. calculate_loss = False
  1039. if labels is not None:
  1040. calculate_loss = True
  1041. is_supervised = not self.config.num_aggregation_labels > 0 or not self.config.use_answer_as_supervision
  1042. # Semi-supervised cell selection in case of no aggregation:
  1043. # If the answer (the denotation) appears directly in the table we might
  1044. # select the answer without applying any aggregation function. There are
  1045. # some ambiguous cases, see utils._calculate_aggregate_mask for more info.
  1046. # `aggregate_mask` is 1 for examples where we chose to aggregate and 0
  1047. # for examples where we chose to select the answer directly.
  1048. # `labels` encodes the positions of the answer appearing in the table.
  1049. if is_supervised:
  1050. aggregate_mask = None
  1051. else:
  1052. if float_answer is not None:
  1053. assert labels.shape[0] == float_answer.shape[0], (
  1054. "Make sure the answers are a FloatTensor of shape (batch_size,)"
  1055. )
  1056. # <float32>[batch_size]
  1057. aggregate_mask = _calculate_aggregate_mask(
  1058. float_answer,
  1059. pooled_output,
  1060. self.config.cell_selection_preference,
  1061. labels,
  1062. self.aggregation_classifier,
  1063. )
  1064. else:
  1065. raise ValueError("You have to specify float answers in order to calculate the aggregate mask")
  1066. # Cell selection log-likelihood
  1067. if self.config.average_logits_per_cell:
  1068. logits_per_cell, _ = reduce_mean(logits, cell_index)
  1069. logits = gather(logits_per_cell, cell_index)
  1070. dist_per_token = torch.distributions.Bernoulli(logits=logits)
  1071. # Compute cell selection loss per example.
  1072. selection_loss_per_example = None
  1073. if not self.config.select_one_column:
  1074. weight = torch.where(
  1075. labels == 0,
  1076. torch.ones_like(labels, dtype=torch.float32),
  1077. self.config.positive_label_weight * torch.ones_like(labels, dtype=torch.float32),
  1078. )
  1079. selection_loss_per_token = -dist_per_token.log_prob(labels) * weight
  1080. selection_loss_per_example = torch.sum(selection_loss_per_token * input_mask_float, dim=1) / (
  1081. torch.sum(input_mask_float, dim=1) + EPSILON_ZERO_DIVISION
  1082. )
  1083. else:
  1084. selection_loss_per_example, logits = _single_column_cell_selection_loss(
  1085. logits, column_logits, labels, cell_index, col_index, cell_mask
  1086. )
  1087. dist_per_token = torch.distributions.Bernoulli(logits=logits)
  1088. # Supervised cell selection
  1089. if self.config.disable_per_token_loss:
  1090. pass
  1091. elif is_supervised:
  1092. total_loss += torch.mean(selection_loss_per_example)
  1093. else:
  1094. # For the not supervised case, do not assign loss for cell selection
  1095. total_loss += torch.mean(selection_loss_per_example * (1.0 - aggregate_mask))
  1096. # Semi-supervised regression loss and supervised loss for aggregations
  1097. if self.config.num_aggregation_labels > 0:
  1098. if is_supervised:
  1099. # Note that `aggregate_mask` is None if the setting is supervised.
  1100. if aggregation_labels is not None:
  1101. assert labels.shape[0] == aggregation_labels.shape[0], (
  1102. "Make sure the aggregation labels are a LongTensor of shape (batch_size,)"
  1103. )
  1104. per_example_additional_loss = _calculate_aggregation_loss(
  1105. logits_aggregation,
  1106. aggregate_mask,
  1107. aggregation_labels,
  1108. self.config.use_answer_as_supervision,
  1109. self.config.num_aggregation_labels,
  1110. self.config.aggregation_loss_weight,
  1111. )
  1112. else:
  1113. raise ValueError(
  1114. "You have to specify aggregation labels in order to calculate the aggregation loss"
  1115. )
  1116. else:
  1117. # Set aggregation labels to zeros
  1118. aggregation_labels = torch.zeros(labels.shape[0], dtype=torch.long, device=labels.device)
  1119. per_example_additional_loss = _calculate_aggregation_loss(
  1120. logits_aggregation,
  1121. aggregate_mask,
  1122. aggregation_labels,
  1123. self.config.use_answer_as_supervision,
  1124. self.config.num_aggregation_labels,
  1125. self.config.aggregation_loss_weight,
  1126. )
  1127. if self.config.use_answer_as_supervision:
  1128. if numeric_values is not None and numeric_values_scale is not None:
  1129. assert numeric_values.shape == numeric_values_scale.shape
  1130. # Add regression loss for numeric answers which require aggregation.
  1131. answer_loss, large_answer_loss_mask = _calculate_regression_loss(
  1132. float_answer,
  1133. aggregate_mask,
  1134. dist_per_token,
  1135. numeric_values,
  1136. numeric_values_scale,
  1137. table_mask_float,
  1138. logits_aggregation,
  1139. self.config,
  1140. )
  1141. per_example_additional_loss += answer_loss
  1142. # Zero loss for examples with answer_loss > cutoff.
  1143. per_example_additional_loss *= large_answer_loss_mask
  1144. else:
  1145. raise ValueError(
  1146. "You have to specify numeric values and numeric values scale in order to calculate the"
  1147. " regression loss"
  1148. )
  1149. total_loss += torch.mean(per_example_additional_loss)
  1150. else:
  1151. # if no label ids are provided, set them to zeros in order to properly compute logits
  1152. labels = torch.zeros_like(logits)
  1153. _, logits = _single_column_cell_selection_loss(
  1154. logits, column_logits, labels, cell_index, col_index, cell_mask
  1155. )
  1156. if not return_dict:
  1157. output = (logits, logits_aggregation) + outputs[2:]
  1158. return ((total_loss,) + output) if calculate_loss else output
  1159. return TableQuestionAnsweringOutput(
  1160. loss=total_loss if calculate_loss else None,
  1161. logits=logits,
  1162. logits_aggregation=logits_aggregation,
  1163. hidden_states=outputs.hidden_states,
  1164. attentions=outputs.attentions,
  1165. )
  1166. @auto_docstring(
  1167. custom_intro="""
  1168. Tapas Model with a sequence classification head on top (a linear layer on top of the pooled output), e.g. for table
  1169. entailment tasks, such as TabFact (Chen et al., 2020).
  1170. """
  1171. )
  1172. class TapasForSequenceClassification(TapasPreTrainedModel):
  1173. def __init__(self, config):
  1174. super().__init__(config)
  1175. self.num_labels = config.num_labels
  1176. self.tapas = TapasModel(config)
  1177. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  1178. self.classifier = nn.Linear(config.hidden_size, config.num_labels)
  1179. # Initialize weights and apply final processing
  1180. self.post_init()
  1181. @auto_docstring
  1182. def forward(
  1183. self,
  1184. input_ids: Optional[torch.LongTensor] = None,
  1185. attention_mask: Optional[torch.FloatTensor] = None,
  1186. token_type_ids: Optional[torch.LongTensor] = None,
  1187. position_ids: Optional[torch.LongTensor] = None,
  1188. head_mask: Optional[torch.FloatTensor] = None,
  1189. inputs_embeds: Optional[torch.FloatTensor] = None,
  1190. labels: Optional[torch.LongTensor] = None,
  1191. output_attentions: Optional[bool] = None,
  1192. output_hidden_states: Optional[bool] = None,
  1193. return_dict: Optional[bool] = None,
  1194. ) -> Union[tuple[torch.Tensor], SequenceClassifierOutput]:
  1195. r"""
  1196. token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length, 7)`, *optional*):
  1197. Token indices that encode tabular structure. Indices can be obtained using [`AutoTokenizer`]. See this
  1198. class for more info.
  1199. [What are token type IDs?](../glossary#token-type-ids)
  1200. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1201. Indices of positions of each input sequence tokens in the position embeddings. If
  1202. `reset_position_index_per_cell` of [`TapasConfig`] is set to `True`, relative position embeddings will be
  1203. used. Selected in the range `[0, config.max_position_embeddings - 1]`.
  1204. [What are position IDs?](../glossary#position-ids)
  1205. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1206. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  1207. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  1208. `config.num_labels > 1` a classification loss is computed (Cross-Entropy). Note: this is called
  1209. "classification_class_index" in the original implementation.
  1210. Examples:
  1211. ```python
  1212. >>> from transformers import AutoTokenizer, TapasForSequenceClassification
  1213. >>> import torch
  1214. >>> import pandas as pd
  1215. >>> tokenizer = AutoTokenizer.from_pretrained("google/tapas-base-finetuned-tabfact")
  1216. >>> model = TapasForSequenceClassification.from_pretrained("google/tapas-base-finetuned-tabfact")
  1217. >>> data = {
  1218. ... "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"],
  1219. ... "Age": ["56", "45", "59"],
  1220. ... "Number of movies": ["87", "53", "69"],
  1221. ... }
  1222. >>> table = pd.DataFrame.from_dict(data)
  1223. >>> queries = [
  1224. ... "There is only one actor who is 45 years old",
  1225. ... "There are 3 actors which played in more than 60 movies",
  1226. ... ]
  1227. >>> inputs = tokenizer(table=table, queries=queries, padding="max_length", return_tensors="pt")
  1228. >>> labels = torch.tensor([1, 0]) # 1 means entailed, 0 means refuted
  1229. >>> outputs = model(**inputs, labels=labels)
  1230. >>> loss = outputs.loss
  1231. >>> logits = outputs.logits
  1232. ```"""
  1233. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1234. outputs = self.tapas(
  1235. input_ids,
  1236. attention_mask=attention_mask,
  1237. token_type_ids=token_type_ids,
  1238. position_ids=position_ids,
  1239. head_mask=head_mask,
  1240. inputs_embeds=inputs_embeds,
  1241. output_attentions=output_attentions,
  1242. output_hidden_states=output_hidden_states,
  1243. return_dict=return_dict,
  1244. )
  1245. pooled_output = outputs[1]
  1246. pooled_output = self.dropout(pooled_output)
  1247. logits = self.classifier(pooled_output)
  1248. loss = None
  1249. if labels is not None:
  1250. if self.config.problem_type is None:
  1251. if self.num_labels == 1:
  1252. self.config.problem_type = "regression"
  1253. elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
  1254. self.config.problem_type = "single_label_classification"
  1255. else:
  1256. self.config.problem_type = "multi_label_classification"
  1257. if self.config.problem_type == "regression":
  1258. loss_fct = MSELoss()
  1259. if self.num_labels == 1:
  1260. loss = loss_fct(logits.squeeze(), labels.squeeze())
  1261. else:
  1262. loss = loss_fct(logits, labels)
  1263. elif self.config.problem_type == "single_label_classification":
  1264. loss_fct = CrossEntropyLoss()
  1265. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  1266. elif self.config.problem_type == "multi_label_classification":
  1267. loss_fct = BCEWithLogitsLoss()
  1268. loss = loss_fct(logits, labels)
  1269. if not return_dict:
  1270. output = (logits,) + outputs[2:]
  1271. return ((loss,) + output) if loss is not None else output
  1272. return SequenceClassifierOutput(
  1273. loss=loss,
  1274. logits=logits,
  1275. hidden_states=outputs.hidden_states,
  1276. attentions=outputs.attentions,
  1277. )
  1278. """ TAPAS utilities."""
  1279. class AverageApproximationFunction(str, enum.Enum):
  1280. RATIO = "ratio"
  1281. FIRST_ORDER = "first_order"
  1282. SECOND_ORDER = "second_order"
  1283. # Beginning of everything related to segmented tensors
  1284. class IndexMap:
  1285. """Index grouping entries within a tensor."""
  1286. def __init__(self, indices, num_segments, batch_dims=0):
  1287. """
  1288. Creates an index
  1289. Args:
  1290. indices (`torch.LongTensor`, same shape as a *values* Tensor to which the indices refer):
  1291. Tensor containing the indices.
  1292. num_segments (`torch.LongTensor`):
  1293. Scalar tensor, the number of segments. All elements in a batched segmented tensor must have the same
  1294. number of segments (although many segments can be empty).
  1295. batch_dims (`int`, *optional*, defaults to 0):
  1296. The number of batch dimensions. The first *batch_dims* dimensions of a SegmentedTensor are treated as
  1297. batch dimensions. Segments in different batch elements are always distinct even if they have the same
  1298. index.
  1299. """
  1300. self.indices = torch.as_tensor(indices, device=indices.device)
  1301. self.num_segments = torch.as_tensor(num_segments, device=indices.device)
  1302. self.batch_dims = batch_dims
  1303. def batch_shape(self):
  1304. return self.indices.size()[: self.batch_dims] # returns a torch.Size object
  1305. class ProductIndexMap(IndexMap):
  1306. """The product of two indices."""
  1307. def __init__(self, outer_index, inner_index):
  1308. """
  1309. Combines indices i and j into pairs (i, j). The result is an index where each segment (i, j) is the
  1310. intersection of segments i and j. For example if the inputs represent table cells indexed by respectively rows
  1311. and columns the output will be a table indexed by (row, column) pairs, i.e. by cell. The implementation
  1312. combines indices {0, .., n - 1} and {0, .., m - 1} into {0, .., nm - 1}. The output has *num_segments* equal to
  1313. *outer_index.num_segments* * *inner_index.num_segments*
  1314. Args:
  1315. outer_index (`IndexMap`):
  1316. IndexMap.
  1317. inner_index (`IndexMap`):
  1318. IndexMap, must have the same shape as *outer_index*.
  1319. """
  1320. if outer_index.batch_dims != inner_index.batch_dims:
  1321. raise ValueError("outer_index.batch_dims and inner_index.batch_dims must be the same.")
  1322. super().__init__(
  1323. indices=(inner_index.indices + outer_index.indices * inner_index.num_segments),
  1324. num_segments=inner_index.num_segments * outer_index.num_segments,
  1325. batch_dims=inner_index.batch_dims,
  1326. )
  1327. self.outer_index = outer_index
  1328. self.inner_index = inner_index
  1329. def project_outer(self, index):
  1330. """Projects an index with the same index set onto the outer components."""
  1331. indices = torch.div(index.indices, self.inner_index.num_segments, rounding_mode="floor").type(torch.long)
  1332. return IndexMap(indices=indices, num_segments=self.outer_index.num_segments, batch_dims=index.batch_dims)
  1333. def project_inner(self, index):
  1334. """Projects an index with the same index set onto the inner components."""
  1335. return IndexMap(
  1336. indices=torch.fmod(index.indices, self.inner_index.num_segments)
  1337. .type(torch.float)
  1338. .floor()
  1339. .type(torch.long),
  1340. num_segments=self.inner_index.num_segments,
  1341. batch_dims=index.batch_dims,
  1342. )
  1343. def gather(values, index, name="segmented_gather"):
  1344. """
  1345. Gathers from *values* using the index map. For each element in the domain of the index map this operation looks up
  1346. a value for that index in *values*. Two elements from the same segment always get assigned the same value.
  1347. Args:
  1348. values (`torch.Tensor` of shape (B1, ..., Bn, num_segments, V1, ...)):
  1349. Tensor with segment values.
  1350. index (`IndexMap` of shape (B1, ..., Bn, I1, ..., Ik)):
  1351. IndexMap.
  1352. name (`str`, *optional*, defaults to 'segmented_gather'):
  1353. Name for the operation. Currently not used
  1354. Returns:
  1355. `tuple(torch.Tensor)`: Tensor of shape (B1, ..., Bn, I1, ..., Ik, V1, ...) with the gathered values.
  1356. """
  1357. indices = index.indices
  1358. # first, check whether the indices of the index represent scalar values (i.e. not vectorized)
  1359. if len(values.shape[index.batch_dims :]) < 2:
  1360. return torch.gather(
  1361. values,
  1362. index.batch_dims,
  1363. indices.view(
  1364. values.size()[0], -1
  1365. ), # torch.gather expects index to have the same number of dimensions as values
  1366. ).view(indices.size())
  1367. else:
  1368. # this means we have a vectorized version
  1369. # we have to adjust the index
  1370. indices = indices.unsqueeze(-1).expand(values.shape)
  1371. return torch.gather(values, index.batch_dims, indices)
  1372. def flatten(index, name="segmented_flatten"):
  1373. """
  1374. Flattens a batched index map (which is typically of shape batch_size, seq_length) to a 1d index map. This operation
  1375. relabels the segments to keep batch elements distinct. The k-th batch element will have indices shifted by
  1376. *num_segments* * (k - 1). The result is a tensor with *num_segments* multiplied by the number of elements in the
  1377. batch.
  1378. Args:
  1379. index (`IndexMap`):
  1380. IndexMap to flatten.
  1381. name (`str`, *optional*, defaults to 'segmented_flatten'):
  1382. Name for the operation. Currently not used
  1383. Returns:
  1384. (`IndexMap`): The flattened IndexMap.
  1385. """
  1386. # first, get batch_size as scalar tensor
  1387. batch_size = torch.prod(torch.tensor(list(index.batch_shape())))
  1388. # next, create offset as 1-D tensor of length batch_size,
  1389. # and multiply element-wise by num segments (to offset different elements in the batch) e.g. if batch size is 2: [0, 64]
  1390. offset = torch.arange(start=0, end=batch_size, device=index.num_segments.device) * index.num_segments
  1391. offset = offset.view(index.batch_shape())
  1392. for _ in range(index.batch_dims, len(index.indices.size())): # typically range(1,2)
  1393. offset = offset.unsqueeze(-1)
  1394. indices = offset + index.indices
  1395. return IndexMap(indices=indices.view(-1), num_segments=index.num_segments * batch_size, batch_dims=0)
  1396. def range_index_map(batch_shape, num_segments, name="range_index_map"):
  1397. """
  1398. Constructs an index map equal to range(num_segments).
  1399. Args:
  1400. batch_shape (`torch.Size`):
  1401. Batch shape
  1402. num_segments (`int`):
  1403. Number of segments
  1404. name (`str`, *optional*, defaults to 'range_index_map'):
  1405. Name for the operation. Currently not used
  1406. Returns:
  1407. (`IndexMap`): IndexMap of shape batch_shape with elements equal to range(num_segments).
  1408. """
  1409. device = num_segments.device if torch.is_tensor(num_segments) else "cpu"
  1410. batch_shape = torch.as_tensor(
  1411. batch_shape, dtype=torch.long, device=device
  1412. ) # create a rank 1 tensor vector containing batch_shape (e.g. [2])
  1413. assert len(batch_shape.size()) == 1
  1414. num_segments = torch.as_tensor(
  1415. num_segments, device=device
  1416. ) # create a rank 0 tensor (scalar) containing num_segments (e.g. 64)
  1417. assert len(num_segments.size()) == 0
  1418. indices = torch.arange(
  1419. start=0, end=num_segments, device=num_segments.device
  1420. ) # create a rank 1 vector with num_segments elements
  1421. new_tensor = torch.cat(
  1422. [torch.ones_like(batch_shape, dtype=torch.long, device=num_segments.device), num_segments.unsqueeze(dim=0)],
  1423. dim=0,
  1424. )
  1425. # new_tensor is just a vector of [1 64] for example (assuming only 1 batch dimension)
  1426. new_shape = [int(x) for x in new_tensor.tolist()]
  1427. indices = indices.view(new_shape)
  1428. multiples = torch.cat([batch_shape, torch.as_tensor([1], device=device)], dim=0)
  1429. indices = indices.repeat(multiples.tolist())
  1430. # equivalent (in Numpy:)
  1431. # indices = torch.as_tensor(np.tile(indices.numpy(), multiples.tolist()))
  1432. return IndexMap(indices=indices, num_segments=num_segments, batch_dims=list(batch_shape.size())[0])
  1433. def _segment_reduce(values, index, segment_reduce_fn, name):
  1434. """
  1435. Applies a segment reduction segment-wise.
  1436. Args:
  1437. values (`torch.Tensor`):
  1438. Tensor with segment values.
  1439. index (`IndexMap`):
  1440. IndexMap.
  1441. segment_reduce_fn (`str`):
  1442. Name for the reduce operation. One of "sum", "mean", "max" or "min".
  1443. name (`str`):
  1444. Name for the operation. Currently not used
  1445. Returns:
  1446. (`IndexMap`): IndexMap of shape batch_shape with elements equal to range(num_segments).
  1447. """
  1448. # Flatten the batch dimensions, as segments ops (scatter) do not support batching.
  1449. # However if `values` has extra dimensions to the right keep them
  1450. # unflattened. Segmented ops support vector-valued operations.
  1451. flat_index = flatten(index)
  1452. vector_shape = values.size()[len(index.indices.size()) :] # torch.Size object
  1453. flattened_shape = torch.cat(
  1454. [torch.as_tensor([-1], dtype=torch.long), torch.as_tensor(vector_shape, dtype=torch.long)], dim=0
  1455. )
  1456. # changed "view" by "reshape" in the following line
  1457. flat_values = values.reshape(flattened_shape.tolist())
  1458. out = torch.zeros(int(flat_index.num_segments), dtype=torch.float, device=flat_values.device)
  1459. segment_means = out.scatter_reduce(
  1460. dim=0, index=flat_index.indices.long(), src=flat_values.float(), reduce=segment_reduce_fn, include_self=False
  1461. )
  1462. device = index.num_segments.device
  1463. # Unflatten the values.
  1464. new_shape = torch.cat(
  1465. [
  1466. torch.as_tensor(index.batch_shape(), dtype=torch.long, device=device),
  1467. torch.as_tensor([index.num_segments], dtype=torch.long, device=device),
  1468. torch.as_tensor(vector_shape, dtype=torch.long, device=device),
  1469. ],
  1470. dim=0,
  1471. )
  1472. output_values = segment_means.clone().view(new_shape.tolist()).to(values.dtype)
  1473. output_index = range_index_map(index.batch_shape(), index.num_segments)
  1474. return output_values, output_index
  1475. def reduce_sum(values, index, name="segmented_reduce_sum"):
  1476. """
  1477. Sums a tensor over its segments.
  1478. Outputs 0 for empty segments.
  1479. This operations computes the sum over segments, with support for:
  1480. - Batching using the first dimensions [B1, B2, ..., Bn]. Each element in a batch can have different indices.
  1481. - Vectorization using the last dimension [V1, V2, ...]. If they are present, the output will be a sum of
  1482. vectors rather than scalars. Only the middle dimensions [I1, ..., Ik] are reduced by the operation.
  1483. Args:
  1484. values (`torch.Tensor` of shape [B1, B2, ..., Bn, I1, .., Ik, V1, V2, ..]):
  1485. Tensor containing the values of which the sum must be taken segment-wise.
  1486. index (`IndexMap`, indices are of shape [B1, B2, ..., Bn, I1, .., Ik].):
  1487. Index defining the segments.
  1488. name (`str`, *optional*, defaults to 'segmented_reduce_sum'):
  1489. Name for the operation. Currently not used
  1490. Returns:
  1491. output_values (`torch.Tensor`of shape [B1, B2, ..., Bn, num_segments, V1, V2, ..]): Tensor containing the
  1492. output values. output_index (`IndexMap`): IndexMap with shape [B1, B2, ..., Bn, num_segments]. .
  1493. """
  1494. return _segment_reduce(values, index, "sum", name)
  1495. def reduce_mean(values, index, name="segmented_reduce_mean"):
  1496. """
  1497. Averages a tensor over its segments.
  1498. Outputs 0 for empty segments.
  1499. This operations computes the mean over segments, with support for:
  1500. - Batching using the first dimensions [B1, B2, ..., Bn]. Each element in a batch can have different indices.
  1501. - Vectorization using the last dimension [V1, V2, ...]. If they are present, the output will be a mean of
  1502. vectors rather than scalars.
  1503. Only the middle dimensions [I1, ..., Ik] are reduced by the operation.
  1504. Args:
  1505. values (`torch.Tensor` of shape [B1, B2, ..., Bn, I1, .., Ik, V1, V2, ..]):
  1506. Tensor containing the values of which the mean must be taken segment-wise.
  1507. index (`IndexMap`, indices are of shape [B1, B2, ..., Bn, I1, .., Ik].):
  1508. Index defining the segments.
  1509. name (`str`, *optional*, defaults to 'segmented_reduce_sum'):
  1510. Name for the operation. Currently not used
  1511. Returns:
  1512. output_values (`torch.Tensor`of shape [B1, B2, ..., Bn, num_segments, V1, V2, ..]): Tensor containing the
  1513. output values. output_index (`IndexMap`): IndexMap with shape [B1, B2, ..., Bn, num_segments].
  1514. """
  1515. return _segment_reduce(values, index, "mean", name)
  1516. def reduce_max(values, index, name="segmented_reduce_max"):
  1517. """
  1518. Computes the maximum over segments.
  1519. This operation computes the maximum over segments, with support for:
  1520. - Batching using the first dimensions [B1, B2, ..., Bn]. Each element in a batch can have different indices.
  1521. - Vectorization using the last dimension [V1, V2, ...]. If they are present, the output will be an element-wise
  1522. maximum of vectors rather than scalars.
  1523. Only the middle dimensions [I1, ..., Ik] are reduced by the operation.
  1524. Args:
  1525. values (`torch.Tensor` of shape [B1, B2, ..., Bn, I1, .., Ik, V1, V2, ..]):
  1526. Tensor containing the values of which the max must be taken segment-wise.
  1527. index (`IndexMap`, indices are of shape [B1, B2, ..., Bn, I1, .., Ik].):
  1528. Index defining the segments.
  1529. name (`str`, *optional*, defaults to 'segmented_reduce_sum'):
  1530. Name for the operation. Currently not used
  1531. Returns:
  1532. output_values (`torch.Tensor`of shape [B1, B2, ..., Bn, num_segments, V1, V2, ..]): Tensor containing the
  1533. output values. output_index (`IndexMap`): IndexMap with shape [B1, B2, ..., Bn, num_segments].
  1534. """
  1535. return _segment_reduce(values, index, "amax", name)
  1536. def reduce_min(values, index, name="segmented_reduce_min"):
  1537. """
  1538. Computes the minimum over segments.
  1539. This operations computes the minimum over segments, with support for:
  1540. - Batching using the first dimensions [B1, B2, ..., Bn]. Each element in a batch can have different indices.
  1541. - Vectorization using the last dimension [V1, V2, ...]. If they are present, the output will be an element-wise
  1542. minimum of vectors rather than scalars.
  1543. Only the middle dimensions [I1, ..., Ik] are reduced by the operation.
  1544. Args:
  1545. values (`torch.Tensor` of shape [B1, B2, ..., Bn, I1, .., Ik, V1, V2, ..]):
  1546. Tensor containing the values of which the min must be taken segment-wise.
  1547. index (`IndexMap`, indices are of shape [B1, B2, ..., Bn, I1, .., Ik].):
  1548. Index defining the segments.
  1549. name (`str`, *optional*, defaults to 'segmented_reduce_sum'):
  1550. Name for the operation. Currently not used
  1551. Returns:
  1552. output_values (`torch.Tensor`of shape [B1, B2, ..., Bn, num_segments, V1, V2, ..]): Tensor containing the
  1553. output values. output_index (`IndexMap`): IndexMap with shape [B1, B2, ..., Bn, num_segments].
  1554. """
  1555. return _segment_reduce(values, index, "amin", name)
  1556. # End of everything related to segmented tensors
  1557. def compute_column_logits(
  1558. sequence_output, column_output_weights, column_output_bias, cell_index, cell_mask, allow_empty_column_selection
  1559. ):
  1560. """
  1561. Computes the column logits.
  1562. Args:
  1563. sequence_output (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
  1564. Also known as last_hidden_state. Sequence of hidden-states at the output of the last layer of the model.
  1565. column_output_weights (`torch.FloatTensor` of shape `(hidden_size)`):
  1566. Weights of the linear layer for column selection.
  1567. column_output_bias (`torch.FloatTensor` of shape `()`):
  1568. Bias of the linear layer for column selection.
  1569. cell_index (`ProductIndexMap`):
  1570. Index that groups tokens into cells.
  1571. cell_mask (`torch.FloatTensor` of shape `(batch_size, max_num_rows * max_num_cols)`):
  1572. Mask for cells that exist in the table (i.e. that are not padding).
  1573. allow_empty_column_selection (`bool`):
  1574. Whether to allow not to select any column
  1575. Returns:
  1576. column_logits (`torch.FloatTensor`of shape `(batch_size, max_num_cols)`): Tensor containing the column logits
  1577. for every example in the batch.
  1578. """
  1579. # First, compute the token logits (batch_size, seq_len) - without temperature
  1580. token_logits = torch.einsum("bsj,j->bs", sequence_output, column_output_weights) + column_output_bias
  1581. # Next, average the logits per cell (batch_size, max_num_cols*max_num_rows)
  1582. cell_logits, cell_logits_index = reduce_mean(token_logits, cell_index)
  1583. # Finally, average the logits per column (batch_size, max_num_cols)
  1584. column_index = cell_index.project_inner(cell_logits_index)
  1585. column_logits, out_index = reduce_sum(cell_logits * cell_mask, column_index)
  1586. cell_count, _ = reduce_sum(cell_mask, column_index)
  1587. column_logits /= cell_count + EPSILON_ZERO_DIVISION
  1588. # Mask columns that do not appear in the example.
  1589. is_padding = torch.logical_and(cell_count < 0.5, ~torch.eq(out_index.indices, 0))
  1590. column_logits += CLOSE_ENOUGH_TO_LOG_ZERO * torch.as_tensor(
  1591. is_padding, dtype=torch.float32, device=is_padding.device
  1592. )
  1593. if not allow_empty_column_selection:
  1594. column_logits += CLOSE_ENOUGH_TO_LOG_ZERO * torch.as_tensor(
  1595. torch.eq(out_index.indices, 0), dtype=torch.float32, device=out_index.indices.device
  1596. )
  1597. return column_logits
  1598. def _single_column_cell_selection_loss(token_logits, column_logits, labels, cell_index, col_index, cell_mask):
  1599. """
  1600. Computes the loss for cell selection constrained to a single column. The loss is a hierarchical log-likelihood. The
  1601. model first predicts a column and then selects cells within that column (conditioned on the column). Cells outside
  1602. the selected column are never selected.
  1603. Args:
  1604. token_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
  1605. Tensor containing the logits per token.
  1606. column_logits (`torch.FloatTensor` of shape `(batch_size, max_num_cols)`):
  1607. Tensor containing the logits per column.
  1608. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  1609. Labels per token.
  1610. cell_index (`ProductIndexMap`):
  1611. Index that groups tokens into cells.
  1612. col_index (`IndexMap`):
  1613. Index that groups tokens into columns.
  1614. cell_mask (`torch.FloatTensor` of shape `(batch_size, max_num_rows * max_num_cols)`):
  1615. Mask for cells that exist in the table (i.e. that are not padding).
  1616. Returns:
  1617. selection_loss_per_example (`torch.FloatTensor` of shape `(batch_size,)`): Loss for each example. logits
  1618. (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): New logits which are only allowed to select
  1619. cells in a single column. Logits outside of the most likely column according to *column_logits* will be set to
  1620. a very low value (such that the probabilities are 0).
  1621. """
  1622. # Part 1: column loss
  1623. # First find the column we should select. We use the column with maximum number of selected cells.
  1624. labels_per_column, _ = reduce_sum(torch.as_tensor(labels, dtype=torch.float32, device=labels.device), col_index)
  1625. # shape of labels_per_column is (batch_size, max_num_cols). It contains the number of label ids for every column, for every example
  1626. column_label = torch.argmax(labels_per_column, dim=-1) # shape (batch_size,)
  1627. # Check if there are no selected cells in the column. In that case the model
  1628. # should predict the special column id 0, which means "select nothing".
  1629. no_cell_selected = torch.eq(
  1630. torch.max(labels_per_column, dim=-1)[0], 0
  1631. ) # no_cell_selected is of shape (batch_size,) and equals True
  1632. # if an example of the batch has no cells selected (i.e. if there are no labels set to 1 for that example)
  1633. column_label = torch.where(
  1634. no_cell_selected.view(column_label.size()), torch.zeros_like(column_label), column_label
  1635. )
  1636. column_dist = torch.distributions.Categorical(logits=column_logits) # shape (batch_size, max_num_cols)
  1637. column_loss_per_example = -column_dist.log_prob(column_label)
  1638. # Part 2: cell loss
  1639. # Reduce the labels and logits to per-cell from per-token.
  1640. # logits_per_cell: shape (batch_size, max_num_rows*max_num_cols) i.e. (batch_size, 64*32)
  1641. logits_per_cell, _ = reduce_mean(token_logits, cell_index)
  1642. # labels_per_cell: shape (batch_size, 64*32), indicating whether each cell should be selected (1) or not (0)
  1643. labels_per_cell, labels_index = reduce_max(
  1644. torch.as_tensor(labels, dtype=torch.long, device=labels.device), cell_index
  1645. )
  1646. # Mask for the selected column.
  1647. # column_id_for_cells: shape (batch_size, 64*32), indicating to which column each cell belongs
  1648. column_id_for_cells = cell_index.project_inner(labels_index).indices
  1649. # column_mask: shape (batch_size, 64*32), equal to 1 if cell belongs to column to be selected
  1650. column_mask = torch.as_tensor(
  1651. torch.eq(column_id_for_cells, torch.unsqueeze(column_label, dim=-1)),
  1652. dtype=torch.float32,
  1653. device=cell_mask.device,
  1654. )
  1655. # Compute the log-likelihood for cells, but only for the selected column.
  1656. cell_dist = torch.distributions.Bernoulli(logits=logits_per_cell) # shape (batch_size, 64*32)
  1657. cell_log_prob = cell_dist.log_prob(labels_per_cell.type(torch.float32)) # shape(batch_size, 64*32)
  1658. cell_loss = -torch.sum(cell_log_prob * column_mask * cell_mask, dim=1)
  1659. # We need to normalize the loss by the number of cells in the column.
  1660. cell_loss /= torch.sum(column_mask * cell_mask, dim=1) + EPSILON_ZERO_DIVISION
  1661. selection_loss_per_example = column_loss_per_example
  1662. selection_loss_per_example += torch.where(
  1663. no_cell_selected.view(selection_loss_per_example.size()),
  1664. torch.zeros_like(selection_loss_per_example),
  1665. cell_loss,
  1666. )
  1667. # Set the probs outside the selected column (selected by the *model*)
  1668. # to 0. This ensures backwards compatibility with models that select
  1669. # cells from multiple columns.
  1670. selected_column_id = torch.as_tensor(
  1671. torch.argmax(column_logits, dim=-1), dtype=torch.long, device=column_logits.device
  1672. ) # shape (batch_size,)
  1673. # selected_column_mask: shape (batch_size, 64*32), equal to 1 if cell belongs to column selected by the model
  1674. selected_column_mask = torch.as_tensor(
  1675. torch.eq(column_id_for_cells, torch.unsqueeze(selected_column_id, dim=-1)),
  1676. dtype=torch.float32,
  1677. device=selected_column_id.device,
  1678. )
  1679. # Never select cells with the special column id 0.
  1680. selected_column_mask = torch.where(
  1681. torch.eq(column_id_for_cells, 0).view(selected_column_mask.size()),
  1682. torch.zeros_like(selected_column_mask),
  1683. selected_column_mask,
  1684. )
  1685. new_logits_per_cell = logits_per_cell + CLOSE_ENOUGH_TO_LOG_ZERO * (1.0 - cell_mask * selected_column_mask)
  1686. logits = gather(new_logits_per_cell, cell_index)
  1687. return selection_loss_per_example, logits
  1688. def compute_token_logits(sequence_output, temperature, output_weights, output_bias):
  1689. """
  1690. Computes logits per token
  1691. Args:
  1692. sequence_output (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
  1693. Also known as last_hidden_state. Sequence of hidden-states at the output of the last layer of the model.
  1694. temperature (`float`):
  1695. Temperature for the Bernoulli distribution.
  1696. output_weights (`torch.FloatTensor` of shape `(hidden_size,)`):
  1697. Weights of the linear layer for cell selection.
  1698. output_bias (`torch.FloatTensor` of shape `()`):
  1699. Bias of the linear layer for cell selection
  1700. Returns:
  1701. logits (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): Logits per token.
  1702. """
  1703. logits = (torch.einsum("bsj,j->bs", sequence_output, output_weights) + output_bias) / temperature
  1704. return logits
  1705. def _calculate_aggregate_mask(answer, pooled_output, cell_selection_preference, labels, aggregation_classifier):
  1706. """
  1707. Finds examples where the model should select cells with no aggregation.
  1708. Returns a mask that determines for which examples should the model select answers directly from the table, without
  1709. any aggregation function. If the answer is a piece of text the case is unambiguous as aggregation functions only
  1710. apply to numbers. If the answer is a number but does not appear in the table then we must use some aggregation
  1711. case. The ambiguous case is when the answer is a number that also appears in the table. In this case we use the
  1712. aggregation function probabilities predicted by the model to decide whether to select or aggregate. The threshold
  1713. for this is a hyperparameter *cell_selection_preference*
  1714. Args:
  1715. answer (`torch.FloatTensor` of shape `(batch_size, )`):
  1716. Answer for every example in the batch. Nan if there is no scalar answer.
  1717. pooled_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`):
  1718. Output of the pooler (BertPooler) on top of the encoder layer.
  1719. cell_selection_preference (`float`):
  1720. Preference for cell selection in ambiguous cases.
  1721. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  1722. Labels per token. aggregation_classifier (`torch.nn.Linear`): Aggregation head
  1723. Returns:
  1724. aggregate_mask (`torch.FloatTensor` of shape `(batch_size,)`): A mask set to 1 for examples that should use
  1725. aggregation functions.
  1726. """
  1727. # torch.FloatTensor(batch_size,)
  1728. aggregate_mask_init = torch.logical_not(torch.isnan(answer)).type(torch.FloatTensor).to(answer.device)
  1729. logits_aggregation = aggregation_classifier(pooled_output)
  1730. dist_aggregation = torch.distributions.categorical.Categorical(logits=logits_aggregation)
  1731. # Index 0 corresponds to "no aggregation".
  1732. aggregation_ops_total_mass = torch.sum(dist_aggregation.probs[:, 1:], dim=1)
  1733. # Cell selection examples according to current model.
  1734. is_pred_cell_selection = aggregation_ops_total_mass <= cell_selection_preference
  1735. # Examples with non-empty cell selection supervision.
  1736. is_cell_supervision_available = torch.sum(labels, dim=1) > 0
  1737. # torch.where is not equivalent to tf.where (in tensorflow 1)
  1738. # hence the added .view on the condition to match the shape of the first tensor
  1739. aggregate_mask = torch.where(
  1740. torch.logical_and(is_pred_cell_selection, is_cell_supervision_available).view(aggregate_mask_init.size()),
  1741. torch.zeros_like(aggregate_mask_init, dtype=torch.float32),
  1742. aggregate_mask_init,
  1743. )
  1744. aggregate_mask = aggregate_mask.detach()
  1745. return aggregate_mask
  1746. def _calculate_aggregation_loss_known(
  1747. logits_aggregation, aggregate_mask, aggregation_labels, use_answer_as_supervision, num_aggregation_labels
  1748. ):
  1749. """
  1750. Calculates aggregation loss when its type is known during training.
  1751. In the weakly supervised setting, the only known information is that for cell selection examples, "no aggregation"
  1752. should be predicted. For other examples (those that require aggregation), no loss is accumulated. In the setting
  1753. where aggregation type is always known, standard cross entropy loss is accumulated for all examples
  1754. Args:
  1755. logits_aggregation (`torch.FloatTensor` of shape `(batch_size, num_aggregation_labels)`):
  1756. Logits per aggregation operation.
  1757. aggregate_mask (`torch.FloatTensor` of shape `(batch_size, )`):
  1758. A mask set to 1 for examples that should use aggregation functions.
  1759. aggregation_labels (`torch.LongTensor` of shape `(batch_size, )`):
  1760. Aggregation function id for every example in the batch.
  1761. use_answer_as_supervision (`bool`, *optional*):
  1762. Whether to use the answer as the only supervision for aggregation examples.
  1763. num_aggregation_labels (`int`, *optional*, defaults to 0):
  1764. The number of aggregation operators to predict.
  1765. Returns:
  1766. aggregation_loss_known (`torch.FloatTensor` of shape `(batch_size,)`): Aggregation loss (when its type is known
  1767. during training) per example.
  1768. """
  1769. if use_answer_as_supervision:
  1770. # Prepare "no aggregation" targets for cell selection examples.
  1771. target_aggregation = torch.zeros_like(aggregate_mask, dtype=torch.long)
  1772. else:
  1773. # Use aggregation supervision as the target.
  1774. target_aggregation = aggregation_labels
  1775. one_hot_labels = nn.functional.one_hot(target_aggregation, num_classes=num_aggregation_labels).type(torch.float32)
  1776. log_probs = nn.functional.log_softmax(logits_aggregation, dim=-1)
  1777. # torch.FloatTensor[batch_size]
  1778. per_example_aggregation_intermediate = -torch.sum(one_hot_labels * log_probs, dim=-1)
  1779. if use_answer_as_supervision:
  1780. # Accumulate loss only for examples requiring cell selection
  1781. # (no aggregation).
  1782. return per_example_aggregation_intermediate * (1 - aggregate_mask)
  1783. else:
  1784. return per_example_aggregation_intermediate
  1785. def _calculate_aggregation_loss_unknown(logits_aggregation, aggregate_mask):
  1786. """
  1787. Calculates aggregation loss in the case of answer supervision.
  1788. Args:
  1789. logits_aggregation (`torch.FloatTensor` of shape `(batch_size, num_aggregation_labels)`):
  1790. Logits per aggregation operation.
  1791. aggregate_mask (`torch.FloatTensor` of shape `(batch_size, )`):
  1792. A mask set to 1 for examples that should use aggregation functions
  1793. Returns:
  1794. aggregation_loss_unknown (`torch.FloatTensor` of shape `(batch_size,)`): Aggregation loss (in case of answer
  1795. supervision) per example.
  1796. """
  1797. dist_aggregation = torch.distributions.categorical.Categorical(logits=logits_aggregation)
  1798. # Index 0 corresponds to "no aggregation".
  1799. aggregation_ops_total_mass = torch.sum(dist_aggregation.probs[:, 1:], dim=1)
  1800. # Predict some aggregation in case of an answer that needs aggregation.
  1801. # This increases the probability of all aggregation functions, in a way
  1802. # similar to MML, but without considering whether the function gives the
  1803. # correct answer.
  1804. return -torch.log(aggregation_ops_total_mass) * aggregate_mask
  1805. def _calculate_aggregation_loss(
  1806. logits_aggregation,
  1807. aggregate_mask,
  1808. aggregation_labels,
  1809. use_answer_as_supervision,
  1810. num_aggregation_labels,
  1811. aggregation_loss_weight,
  1812. ):
  1813. """
  1814. Calculates the aggregation loss per example.
  1815. Args:
  1816. logits_aggregation (`torch.FloatTensor` of shape `(batch_size, num_aggregation_labels)`):
  1817. Logits per aggregation operation.
  1818. aggregate_mask (`torch.FloatTensor` of shape `(batch_size, )`):
  1819. A mask set to 1 for examples that should use aggregation functions.
  1820. aggregation_labels (`torch.LongTensor` of shape `(batch_size, )`):
  1821. Aggregation function id for every example in the batch.
  1822. use_answer_as_supervision (`bool`, *optional*):
  1823. Whether to use the answer as the only supervision for aggregation examples.
  1824. num_aggregation_labels (`int`, *optional*, defaults to 0):
  1825. The number of aggregation operators to predict.
  1826. aggregation_loss_weight (`float`, *optional*, defaults to 1.0):
  1827. Importance weight for the aggregation loss.
  1828. Returns:
  1829. aggregation_loss (`torch.FloatTensor` of shape `(batch_size,)`): Aggregation loss per example.
  1830. """
  1831. per_example_aggregation_loss = _calculate_aggregation_loss_known(
  1832. logits_aggregation, aggregate_mask, aggregation_labels, use_answer_as_supervision, num_aggregation_labels
  1833. )
  1834. if use_answer_as_supervision:
  1835. # Add aggregation loss for numeric answers that need aggregation.
  1836. per_example_aggregation_loss += _calculate_aggregation_loss_unknown(logits_aggregation, aggregate_mask)
  1837. return aggregation_loss_weight * per_example_aggregation_loss
  1838. def _calculate_expected_result(
  1839. dist_per_cell, numeric_values, numeric_values_scale, input_mask_float, logits_aggregation, config
  1840. ):
  1841. """
  1842. Calculates the expected result given cell and aggregation probabilities.
  1843. Args:
  1844. dist_per_cell (`torch.distributions.Bernoulli`):
  1845. Cell selection distribution for each cell.
  1846. numeric_values (`torch.FloatTensor` of shape `(batch_size, seq_length)`):
  1847. Numeric values of every token. Nan for tokens which are not numeric values.
  1848. numeric_values_scale (`torch.FloatTensor` of shape `(batch_size, seq_length)`):
  1849. Scale of the numeric values of every token.
  1850. input_mask_float (`torch.FloatTensor` of shape `(batch_size, seq_length)`):
  1851. Mask for the table, without question tokens and table headers.
  1852. logits_aggregation (`torch.FloatTensor` of shape `(batch_size, num_aggregation_labels)`):
  1853. Logits per aggregation operation.
  1854. config ([`TapasConfig`]):
  1855. Model configuration class with all the hyperparameters of the model
  1856. Returns:
  1857. expected_result (`torch.FloatTensor` of shape `(batch_size,)`): The expected result per example.
  1858. """
  1859. if config.use_gumbel_for_cells:
  1860. gumbel_dist = torch.distributions.RelaxedBernoulli(
  1861. # The token logits where already divided by the temperature and used for
  1862. # computing cell selection errors so we need to multiply it again here
  1863. temperature=config.temperature,
  1864. logits=dist_per_cell.logits * config.temperature,
  1865. )
  1866. scaled_probability_per_cell = gumbel_dist.sample()
  1867. else:
  1868. scaled_probability_per_cell = dist_per_cell.probs
  1869. # <float32>[batch_size, seq_length]
  1870. scaled_probability_per_cell = (scaled_probability_per_cell / numeric_values_scale) * input_mask_float
  1871. count_result = torch.sum(scaled_probability_per_cell, dim=1)
  1872. numeric_values_masked = torch.where(
  1873. torch.isnan(numeric_values), torch.zeros_like(numeric_values), numeric_values
  1874. ) # Mask non-numeric table values to zero.
  1875. sum_result = torch.sum(scaled_probability_per_cell * numeric_values_masked, dim=1)
  1876. avg_approximation = config.average_approximation_function
  1877. if avg_approximation == AverageApproximationFunction.RATIO:
  1878. average_result = sum_result / (count_result + EPSILON_ZERO_DIVISION)
  1879. elif avg_approximation == AverageApproximationFunction.FIRST_ORDER:
  1880. # The sum of all probabilities except that correspond to other cells
  1881. # Ex here stands for expectation, more explicitly the expectation of the sum of N-1 Bernoulli random variables plus
  1882. # the constant 1, which is computed as adding all N expected values and subtracting the extra one. It corresponds to X_c
  1883. # in Appendix D of the original TAPAS paper which is trying to approximate the average of a random set.
  1884. ex = torch.sum(scaled_probability_per_cell, dim=1, keepdim=True) - scaled_probability_per_cell + 1
  1885. average_result = torch.sum(numeric_values_masked * scaled_probability_per_cell / ex, dim=1)
  1886. elif avg_approximation == AverageApproximationFunction.SECOND_ORDER:
  1887. # The sum of all probabilities except that correspond to other cells
  1888. ex = torch.sum(scaled_probability_per_cell, dim=1, keepdim=True) - scaled_probability_per_cell + 1
  1889. pointwise_var = scaled_probability_per_cell * (1 - scaled_probability_per_cell)
  1890. var = torch.sum(pointwise_var, dim=1, keepdim=True) - pointwise_var
  1891. multiplier = (var / torch.square(ex) + 1) / ex
  1892. average_result = torch.sum(numeric_values_masked * scaled_probability_per_cell * multiplier, dim=1)
  1893. else:
  1894. raise ValueError(f"Invalid average_approximation_function: {config.average_approximation_function}")
  1895. if config.use_gumbel_for_aggregation:
  1896. gumbel_dist = torch.distributions.RelaxedOneHotCategorical(
  1897. config.aggregation_temperature, logits=logits_aggregation[:, 1:]
  1898. )
  1899. # <float32>[batch_size, num_aggregation_labels - 1]
  1900. aggregation_op_only_probs = gumbel_dist.sample()
  1901. else:
  1902. # <float32>[batch_size, num_aggregation_labels - 1]
  1903. aggregation_op_only_probs = nn.functional.softmax(
  1904. logits_aggregation[:, 1:] / config.aggregation_temperature, dim=-1
  1905. )
  1906. all_results = torch.cat(
  1907. [
  1908. torch.unsqueeze(sum_result, dim=1),
  1909. torch.unsqueeze(average_result, dim=1),
  1910. torch.unsqueeze(count_result, dim=1),
  1911. ],
  1912. dim=1,
  1913. )
  1914. expected_result = torch.sum(all_results * aggregation_op_only_probs, dim=1)
  1915. return expected_result
  1916. # PyTorch does not currently support Huber loss with custom delta so we define it ourself
  1917. def huber_loss(input, target, delta: float = 1.0):
  1918. errors = torch.abs(input - target) # shape (batch_size,)
  1919. return torch.where(errors < delta, 0.5 * errors**2, errors * delta - (0.5 * delta**2))
  1920. def _calculate_regression_loss(
  1921. answer,
  1922. aggregate_mask,
  1923. dist_per_cell,
  1924. numeric_values,
  1925. numeric_values_scale,
  1926. input_mask_float,
  1927. logits_aggregation,
  1928. config,
  1929. ):
  1930. """
  1931. Calculates the regression loss per example.
  1932. Args:
  1933. answer (`torch.FloatTensor` of shape `(batch_size,)`):
  1934. Answer for every example in the batch. Nan if there is no scalar answer.
  1935. aggregate_mask (`torch.FloatTensor` of shape `(batch_size,)`):
  1936. A mask set to 1 for examples that should use aggregation functions.
  1937. dist_per_cell (`torch.distributions.Bernoulli`):
  1938. Cell selection distribution for each cell.
  1939. numeric_values (`torch.FloatTensor` of shape `(batch_size, seq_length)`):
  1940. Numeric values of every token. Nan for tokens which are not numeric values.
  1941. numeric_values_scale (`torch.FloatTensor` of shape `(batch_size, seq_length)`):
  1942. Scale of the numeric values of every token.
  1943. input_mask_float (`torch.FloatTensor` of shape `(batch_size, seq_length)`):
  1944. Mask for the table, without question tokens and table headers.
  1945. logits_aggregation (`torch.FloatTensor` of shape `(batch_size, num_aggregation_labels)`):
  1946. Logits per aggregation operation.
  1947. config ([`TapasConfig`]):
  1948. Model configuration class with all the parameters of the model
  1949. Returns:
  1950. per_example_answer_loss_scaled (`torch.FloatTensor` of shape `(batch_size,)`): Scales answer loss for each
  1951. example in the batch. large_answer_loss_mask (`torch.FloatTensor` of shape `(batch_size,)`): A mask which is 1
  1952. for examples for which their answer loss is larger than the answer_loss_cutoff.
  1953. """
  1954. # float32 (batch_size,)
  1955. expected_result = _calculate_expected_result(
  1956. dist_per_cell, numeric_values, numeric_values_scale, input_mask_float, logits_aggregation, config
  1957. )
  1958. # float32 (batch_size,)
  1959. answer_masked = torch.where(torch.isnan(answer), torch.zeros_like(answer), answer)
  1960. if config.use_normalized_answer_loss:
  1961. normalizer = (torch.max(torch.abs(expected_result), torch.abs(answer_masked)) + EPSILON_ZERO_DIVISION).detach()
  1962. normalized_answer_masked = answer_masked / normalizer
  1963. normalized_expected_result = expected_result / normalizer
  1964. per_example_answer_loss = huber_loss(
  1965. normalized_expected_result * aggregate_mask, normalized_answer_masked * aggregate_mask
  1966. )
  1967. else:
  1968. per_example_answer_loss = huber_loss(
  1969. expected_result * aggregate_mask, answer_masked * aggregate_mask, delta=config.huber_loss_delta
  1970. )
  1971. if config.answer_loss_cutoff is None:
  1972. large_answer_loss_mask = torch.ones_like(per_example_answer_loss, dtype=torch.float32)
  1973. else:
  1974. large_answer_loss_mask = torch.where(
  1975. per_example_answer_loss > config.answer_loss_cutoff,
  1976. torch.zeros_like(per_example_answer_loss, dtype=torch.float32),
  1977. torch.ones_like(per_example_answer_loss, dtype=torch.float32),
  1978. )
  1979. per_example_answer_loss_scaled = config.answer_loss_importance * (per_example_answer_loss * aggregate_mask)
  1980. return per_example_answer_loss_scaled, large_answer_loss_mask
  1981. __all__ = [
  1982. "TapasForMaskedLM",
  1983. "TapasForQuestionAnswering",
  1984. "TapasForSequenceClassification",
  1985. "TapasModel",
  1986. "TapasPreTrainedModel",
  1987. "load_tf_weights_in_tapas",
  1988. ]