TAPEX (original) (raw)

PyTorch TensorFlow Flax

This model is in maintenance mode only, we don’t accept any new PRs changing its code.

If you run into any issues running this model, please reinstall the last version that supported this model: v4.30.0. You can do so by running the following command: pip install -U transformers==4.30.0.

Overview

The TAPEX model was proposed in TAPEX: Table Pre-training via Learning a Neural SQL Executor by Qian Liu, Bei Chen, Jiaqi Guo, Morteza Ziyadi, Zeqi Lin, Weizhu Chen, Jian-Guang Lou. TAPEX pre-trains a BART model to solve synthetic SQL queries, after which it can be fine-tuned to answer natural language questions related to tabular data, as well as performing table fact checking.

TAPEX has been fine-tuned on several datasets:

The abstract from the paper is the following:

Recent progress in language model pre-training has achieved a great success via leveraging large-scale unstructured textual data. However, it is still a challenge to apply pre-training on structured tabular data due to the absence of large-scale high-quality tabular data. In this paper, we propose TAPEX to show that table pre-training can be achieved by learning a neural SQL executor over a synthetic corpus, which is obtained by automatically synthesizing executable SQL queries and their execution outputs. TAPEX addresses the data scarcity challenge via guiding the language model to mimic a SQL executor on the diverse, large-scale and high-quality synthetic corpus. We evaluate TAPEX on four benchmark datasets. Experimental results demonstrate that TAPEX outperforms previous table pre-training approaches by a large margin and achieves new state-of-the-art results on all of them. This includes improvements on the weakly-supervised WikiSQL denotation accuracy to 89.5% (+2.3%), the WikiTableQuestions denotation accuracy to 57.5% (+4.8%), the SQA denotation accuracy to 74.5% (+3.5%), and the TabFact accuracy to 84.2% (+3.2%). To our knowledge, this is the first work to exploit table pre-training via synthetic executable programs and to achieve new state-of-the-art results on various downstream tasks.

Usage tips

Usage: inference

Below, we illustrate how to use TAPEX for table question answering. As one can see, one can directly plug in the weights of TAPEX into a BART model. We use the Auto API, which will automatically instantiate the appropriate tokenizer (TapexTokenizer) and model (BartForConditionalGeneration) for us, based on the configuration file of the checkpoint on the hub.

from transformers import AutoTokenizer, AutoModelForSeq2SeqLM import pandas as pd

tokenizer = AutoTokenizer.from_pretrained("microsoft/tapex-large-finetuned-wtq") model = AutoModelForSeq2SeqLM.from_pretrained("microsoft/tapex-large-finetuned-wtq")

data = {"Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], "Number of movies": ["87", "53", "69"]} table = pd.DataFrame.from_dict(data) question = "how many movies does Leonardo Di Caprio have?"

encoding = tokenizer(table, question, return_tensors="pt")

outputs = model.generate(**encoding)

predicted_answer = tokenizer.batch_decode(outputs, skip_special_tokens=True)[0] print(predicted_answer) 53

Note that TapexTokenizer also supports batched inference. Hence, one can provide a batch of different tables/questions, or a batch of a single table and multiple questions, or a batch of a single query and multiple tables. Let’s illustrate this:

data = {"Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], "Number of movies": ["87", "53", "69"]} table = pd.DataFrame.from_dict(data) questions = [ ... "how many movies does Leonardo Di Caprio have?", ... "which actor has 69 movies?", ... "what's the first name of the actor who has 87 movies?", ... ] encoding = tokenizer(table, questions, padding=True, return_tensors="pt")

outputs = model.generate(**encoding)

tokenizer.batch_decode(outputs, skip_special_tokens=True) [' 53', ' george clooney', ' brad pitt']

In case one wants to do table verification (i.e. the task of determining whether a given sentence is supported or refuted by the contents of a table), one can instantiate a BartForSequenceClassification model. TAPEX has checkpoints on the hub fine-tuned on TabFact, an important benchmark for table fact checking (it achieves 84% accuracy). The code example below again leverages the Auto API.

from transformers import AutoTokenizer, AutoModelForSequenceClassification

tokenizer = AutoTokenizer.from_pretrained("microsoft/tapex-large-finetuned-tabfact") model = AutoModelForSequenceClassification.from_pretrained("microsoft/tapex-large-finetuned-tabfact")

data = {"Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], "Number of movies": ["87", "53", "69"]} table = pd.DataFrame.from_dict(data) sentence = "George Clooney has 30 movies"

encoding = tokenizer(table, sentence, return_tensors="pt")

outputs = model(**encoding)

predicted_class_idx = outputs.logits[0].argmax(dim=0).item() print(model.config.id2label[predicted_class_idx]) Refused

TAPEX architecture is the same as BART, except for tokenization. Refer to BART documentation for information on configuration classes and their parameters. TAPEX-specific tokenizer is documented below.

TapexTokenizer

class transformers.TapexTokenizer

< source >

( vocab_file merges_file do_lower_case = True errors = 'replace' bos_token = '' eos_token = '' sep_token = '' cls_token = '' unk_token = '' pad_token = '' mask_token = '' add_prefix_space = False max_cell_length = 15 **kwargs )

Parameters

Construct a TAPEX tokenizer. Based on byte-level Byte-Pair-Encoding (BPE).

This tokenizer can be used to flatten one or more table(s) and concatenate them with one or more related sentences to be used by TAPEX models. The format that the TAPEX tokenizer creates is the following:

sentence col: col1 | col2 | col 3 row 1 : val1 | val2 | val3 row 2 : …

The tokenizer supports a single table + single query, a single table and multiple queries (in which case the table will be duplicated for every query), a single query and multiple tables (in which case the query will be duplicated for every table), and multiple tables and queries. In other words, you can provide a batch of tables + questions to the tokenizer for instance to prepare them for the model.

Tokenization itself is based on the BPE algorithm. It is identical to the one used by BART, RoBERTa and GPT-2.

This tokenizer inherits from PreTrainedTokenizer which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.

__call__

< source >

( table: typing.Union[ForwardRef('pd.DataFrame'), typing.List[ForwardRef('pd.DataFrame')]] = None query: typing.Union[str, typing.List[str], NoneType] = None answer: typing.Union[str, typing.List[str]] = None add_special_tokens: bool = True padding: typing.Union[bool, str, transformers.utils.generic.PaddingStrategy] = False truncation: typing.Union[bool, str, transformers.tokenization_utils_base.TruncationStrategy] = None max_length: typing.Optional[int] = None stride: int = 0 pad_to_multiple_of: typing.Optional[int] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None return_token_type_ids: typing.Optional[bool] = None return_attention_mask: typing.Optional[bool] = None return_overflowing_tokens: bool = False return_special_tokens_mask: bool = False return_offsets_mapping: bool = False return_length: bool = False verbose: bool = True **kwargs )

Parameters

Main method to tokenize and prepare for the model one or several table-sequence pair(s).

save_vocabulary

< source >

( save_directory: str filename_prefix: typing.Optional[str] = None )

< > Update on GitHub