Spaces:
Runtime error
Runtime error
File size: 19,580 Bytes
db5855f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 |
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"source": [
"# Table Question Answering using TAPAS and OpenVINO™\n",
"\n",
"Table Question Answering (Table QA) is the answering a question about an information on a given table. You can use the Table Question Answering models to simulate SQL execution by inputting a table.\n",
"\n",
"In this tutorial we demonstrate how to perform table question answering using OpenVINO. This example based on [TAPAS base model fine-tuned on WikiTable Questions (WTQ)](https://huggingface.co/google/tapas-base-finetuned-wtq) that is based on the paper [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://arxiv.org/abs/2004.02349#:~:text=Answering%20natural%20language%20questions%20over,denotations%20instead%20of%20logical%20forms).\n",
"\n",
"Answering natural language questions over tables is usually seen as a semantic parsing task. To alleviate the collection cost of full logical forms, one popular approach focuses on weak supervision consisting of denotations instead of logical forms. However, training semantic parsers from weak supervision poses difficulties, and in addition, the generated logical forms are only used as an intermediate step prior to retrieving the denotation. In [this paper](https://arxiv.org/pdf/2004.02349.pdf), it is presented TAPAS, an approach to question answering over tables without generating logical forms. TAPAS trains from weak supervision, and predicts the denotation by selecting table cells and optionally applying a corresponding aggregation operator to such selection. TAPAS extends BERT's architecture to encode tables as input, initializes from an effective joint pre-training of text segments and tables crawled from Wikipedia, and is trained end-to-end.\n",
"\n",
"\n",
"\n",
"#### Table of contents:\n",
"\n",
"- [Prerequisites](#Prerequisites)\n",
"- [Use the original model to run an inference](#Use-the-original-model-to-run-an-inference)\n",
"- [Convert the original model to OpenVINO Intermediate Representation (IR) format](#Convert-the-original-model-to-OpenVINO-Intermediate-Representation-(IR)-format)\n",
"- [Run the OpenVINO model](#Run-the-OpenVINO-model)\n",
"- [Interactive inference](#Interactive-inference)\n",
"\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"source": [
"### Prerequisites\n",
"[back to top ⬆️](#Table-of-contents:)\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [],
"source": [
"\n",
"%pip install -q torch \"transformers>=4.31.0\" \"torch>=2.1\" --extra-index-url https://download.pytorch.org/whl/cpu\n",
"%pip install -q \"openvino>=2023.2.0\" \"gradio>=4.0.2\""
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [],
"source": [
"import torch\n",
"from transformers import TapasForQuestionAnswering\n",
"from transformers import TapasTokenizer\n",
"from transformers import pipeline\n",
"import pandas as pd"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"source": [
"Use `TapasForQuestionAnswering.from_pretrained` to download a pretrained model and `TapasTokenizer.from_pretrained` to get a tokenizer."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>Actors</th>\n",
" <th>Number of movies</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>Brad Pitt</td>\n",
" <td>87</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>Leonardo Di Caprio</td>\n",
" <td>53</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>George Clooney</td>\n",
" <td>69</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" Actors Number of movies\n",
"0 Brad Pitt 87\n",
"1 Leonardo Di Caprio 53\n",
"2 George Clooney 69"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"model = TapasForQuestionAnswering.from_pretrained(\"google/tapas-large-finetuned-wtq\")\n",
"tokenizer = TapasTokenizer.from_pretrained(\"google/tapas-large-finetuned-wtq\")\n",
"\n",
"data = {\n",
" \"Actors\": [\"Brad Pitt\", \"Leonardo Di Caprio\", \"George Clooney\"],\n",
" \"Number of movies\": [\"87\", \"53\", \"69\"],\n",
"}\n",
"table = pd.DataFrame.from_dict(data)\n",
"question = \"how many movies does Leonardo Di Caprio have?\"\n",
"table"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"source": [
"### Use the original model to run an inference\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"\n",
"We use [this example](https://huggingface.co/tasks/table-question-answering) to demonstrate how to make an inference. You can use `pipeline` from `transformer` library for this purpose."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The answer is 53\n"
]
}
],
"source": [
"tqa = pipeline(task=\"table-question-answering\", model=model, tokenizer=tokenizer)\n",
"result = tqa(table=table, query=question)\n",
"print(f\"The answer is {result['cells'][0]}\")"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"source": [
"You can read more about the inference output structure in [this documentation](https://huggingface.co/docs/transformers/model_doc/tapas)."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"source": [
"### Convert the original model to OpenVINO Intermediate Representation (IR) format\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"The original model is a PyTorch module, that can be converted with `ov.convert_model` function directly. We also use `ov.save_model` function to serialize the result of conversion."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [],
"source": [
"import openvino as ov\n",
"from pathlib import Path\n",
"\n",
"\n",
"# Define the input shape\n",
"batch_size = 1\n",
"sequence_length = 29\n",
"\n",
"# Modify the input shape of the dummy_input dictionary\n",
"dummy_input = {\n",
" \"input_ids\": torch.zeros((batch_size, sequence_length), dtype=torch.long),\n",
" \"attention_mask\": torch.zeros((batch_size, sequence_length), dtype=torch.long),\n",
" \"token_type_ids\": torch.zeros((batch_size, sequence_length, 7), dtype=torch.long),\n",
"}\n",
"\n",
"\n",
"ov_model_xml_path = Path(\"models/ov_model.xml\")\n",
"\n",
"if not ov_model_xml_path.exists():\n",
" ov_model = ov.convert_model(model, example_input=dummy_input)\n",
" ov.save_model(ov_model, ov_model_xml_path)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"source": [
"### Run the OpenVINO model\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"\n",
"Select a device from dropdown list for running inference using OpenVINO."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "465c49c179c64e2881376a078945f605",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Dropdown(description='Device:', index=2, options=('CPU', 'GPU', 'AUTO'), value='AUTO')"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import ipywidgets as widgets\n",
"\n",
"core = ov.Core()\n",
"\n",
"device = widgets.Dropdown(\n",
" options=core.available_devices + [\"AUTO\"],\n",
" value=\"AUTO\",\n",
" description=\"Device:\",\n",
" disabled=False,\n",
")\n",
"\n",
"device"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"source": [
"We use `ov.compile_model` to make it ready to use for loading on a device. To prepare inputs use the original `tokenizer`."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [],
"source": [
"inputs = tokenizer(table=table, queries=question, padding=\"max_length\", return_tensors=\"pt\")\n",
"\n",
"compiled_model = core.compile_model(ov_model_xml_path, device.value)\n",
"result = compiled_model((inputs[\"input_ids\"], inputs[\"attention_mask\"], inputs[\"token_type_ids\"]))"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"source": [
"Now we should postprocess results. For this, we can use the appropriate part of the code from [`postprocess`](https://github.com/huggingface/transformers/blob/fe2877ce21eb75d34d30664757e2727d7eab817e/src/transformers/pipelines/table_question_answering.py#L393) method of `TableQuestionAnsweringPipeline`."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"53\n"
]
}
],
"source": [
"logits = result[0]\n",
"logits_aggregation = result[1]\n",
"\n",
"\n",
"predictions = tokenizer.convert_logits_to_predictions(inputs, torch.from_numpy(result[0]))\n",
"answer_coordinates_batch = predictions[0]\n",
"aggregators = {}\n",
"aggregators_prefix = {}\n",
"answers = []\n",
"for index, coordinates in enumerate(answer_coordinates_batch):\n",
" cells = [table.iat[coordinate] for coordinate in coordinates]\n",
" aggregator = aggregators.get(index, \"\")\n",
" aggregator_prefix = aggregators_prefix.get(index, \"\")\n",
" answer = {\n",
" \"answer\": aggregator_prefix + \", \".join(cells),\n",
" \"coordinates\": coordinates,\n",
" \"cells\": [table.iat[coordinate] for coordinate in coordinates],\n",
" }\n",
" if aggregator:\n",
" answer[\"aggregator\"] = aggregator\n",
"\n",
" answers.append(answer)\n",
"\n",
"print(answers[0][\"cells\"][0])"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"source": [
"Also, we can use the original pipeline. For this, we should create a wrapper for `TapasForQuestionAnswering` class replacing `forward` method to use the OpenVINO model for inference and methods and attributes of original model class to be integrated into the pipeline."
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"53\n"
]
}
],
"source": [
"from transformers import TapasConfig\n",
"\n",
"\n",
"# get config for pretrained model\n",
"config = TapasConfig.from_pretrained(\"google/tapas-large-finetuned-wtq\")\n",
"\n",
"\n",
"class TapasForQuestionAnswering(TapasForQuestionAnswering): # it is better to keep the class name to avoid warnings\n",
" def __init__(self, ov_model_path):\n",
" super().__init__(config) # pass config from the pretrained model\n",
" self.tqa_model = core.compile_model(ov_model_path, device.value)\n",
"\n",
" def forward(self, input_ids, *, attention_mask, token_type_ids):\n",
" results = self.tqa_model((input_ids, attention_mask, token_type_ids))\n",
"\n",
" return torch.from_numpy(results[0]), torch.from_numpy(results[1])\n",
"\n",
"\n",
"compiled_model = TapasForQuestionAnswering(ov_model_xml_path)\n",
"tqa = pipeline(task=\"table-question-answering\", model=compiled_model, tokenizer=tokenizer)\n",
"print(tqa(table=table, query=question)[\"cells\"][0])"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"source": [
"### Interactive inference\n",
"[back to top ⬆️](#Table-of-contents:)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [],
"source": [
"import requests\n",
"\n",
"import gradio as gr\n",
"import pandas as pd\n",
"\n",
"r = requests.get(\"https://github.com/openvinotoolkit/openvino_notebooks/files/13215688/eu_city_population_top10.csv\")\n",
"\n",
"with open(\"eu_city_population_top10.csv\", \"w\") as f:\n",
" f.write(r.text)\n",
"\n",
"\n",
"def display_table(csv_file_name):\n",
" table = pd.read_csv(csv_file_name.name, delimiter=\",\")\n",
" table = table.astype(str)\n",
"\n",
" return table\n",
"\n",
"\n",
"def highlight_answers(x, coordinates):\n",
" highlighted_table = pd.DataFrame(\"\", index=x.index, columns=x.columns)\n",
" for coordinates_i in coordinates:\n",
" highlighted_table.iloc[coordinates_i[0], coordinates_i[1]] = \"background-color: lightgreen\"\n",
"\n",
" return highlighted_table\n",
"\n",
"\n",
"def infer(query, csv_file_name):\n",
" table = pd.read_csv(csv_file_name.name, delimiter=\",\")\n",
" table = table.astype(str)\n",
"\n",
" result = tqa(table=table, query=query)\n",
" table = table.style.apply(highlight_answers, axis=None, coordinates=result[\"coordinates\"])\n",
"\n",
" return result[\"answer\"], table\n",
"\n",
"\n",
"with gr.Blocks(title=\"TAPAS Table Question Answering\") as demo:\n",
" with gr.Row():\n",
" with gr.Column():\n",
" search_query = gr.Textbox(label=\"Search query\")\n",
" csv_file = gr.File(label=\"CSV file\")\n",
" infer_button = gr.Button(\"Submit\", variant=\"primary\")\n",
" with gr.Column():\n",
" answer = gr.Textbox(label=\"Result\")\n",
" result_csv_file = gr.Dataframe(label=\"All data\")\n",
"\n",
" examples = [\n",
" [\n",
" \"What is the city with the highest population that is not a capital?\",\n",
" \"eu_city_population_top10.csv\",\n",
" ],\n",
" [\"In which country is Madrid?\", \"eu_city_population_top10.csv\"],\n",
" [\n",
" \"In which cities is the population greater than 2,000,000?\",\n",
" \"eu_city_population_top10.csv\",\n",
" ],\n",
" ]\n",
" gr.Examples(examples, inputs=[search_query, csv_file])\n",
"\n",
" # Callbacks\n",
" csv_file.upload(display_table, inputs=csv_file, outputs=result_csv_file)\n",
" csv_file.select(display_table, inputs=csv_file, outputs=result_csv_file)\n",
" csv_file.change(display_table, inputs=csv_file, outputs=result_csv_file)\n",
" infer_button.click(infer, inputs=[search_query, csv_file], outputs=[answer, result_csv_file])\n",
"\n",
"try:\n",
" demo.queue().launch(debug=True)\n",
"except Exception:\n",
" demo.queue().launch(share=True, debug=True)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.10"
},
"openvino_notebooks": {
"imageUrl": "https://github.com/openvinotoolkit/openvino_notebooks/assets/29454499/cda2a126-ad66-40eb-b85f-3e9ceff05190",
"tags": {
"categories": [
"Model Demos"
],
"libraries": [],
"other": [],
"tasks": [
"Table Question Answering"
]
}
},
"widgets": {
"application/vnd.jupyter.widget-state+json": {
"state": {},
"version_major": 2,
"version_minor": 0
}
}
},
"nbformat": 4,
"nbformat_minor": 4
}
|