File size: 23,830 Bytes
b2b0691 |
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 619 620 |
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"gpuType": "T4"
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
},
"accelerator": "GPU"
},
"cells": [
{
"cell_type": "markdown",
"source": [
"# Setting up the environment"
],
"metadata": {
"id": "g0P2N4KjS4Dz"
}
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"id": "wkVgiRJtStA9"
},
"outputs": [],
"source": [
"!pip install pymupdf --quiet"
]
},
{
"cell_type": "code",
"source": [
"import re\n",
"import warnings\n",
"\n",
"import fitz\n",
"import nltk\n",
"import torch\n",
"from nltk.tokenize import sent_tokenize\n",
"from peft import AutoPeftModelForSeq2SeqLM\n",
"from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, logging\n",
"\n",
"CKPT_PATH = \"facebook/bart-large-cnn\" # Path to the fine-tuned base model\n",
"HF_REPO_PATH = \"spolivin/bart-arxiv-lora\" # Path to the repo where LoRA adapters are saved\n",
"\n",
"warnings.filterwarnings(\"ignore\")\n",
"logging.set_verbosity_error()\n",
"nltk.download(\"punkt_tab\")\n",
"nltk.download(\"punkt\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "XfYs8aczk6QN",
"outputId": "4be63c1f-450a-4627-c1f6-c5f5872e30c0"
},
"execution_count": 2,
"outputs": [
{
"output_type": "stream",
"name": "stderr",
"text": [
"[nltk_data] Downloading package punkt_tab to /root/nltk_data...\n",
"[nltk_data] Package punkt_tab is already up-to-date!\n",
"[nltk_data] Downloading package punkt to /root/nltk_data...\n",
"[nltk_data] Package punkt is already up-to-date!\n"
]
},
{
"output_type": "execute_result",
"data": {
"text/plain": [
"True"
]
},
"metadata": {},
"execution_count": 2
}
]
},
{
"cell_type": "markdown",
"source": [
"# Loading models to be tested"
],
"metadata": {
"id": "MHUC9wjpS7L8"
}
},
{
"cell_type": "code",
"source": [
"tokenizer = AutoTokenizer.from_pretrained(CKPT_PATH)\n",
"original_model = AutoModelForSeq2SeqLM.from_pretrained(CKPT_PATH)\n",
"\n",
"lora_model = AutoPeftModelForSeq2SeqLM.from_pretrained(HF_REPO_PATH)"
],
"metadata": {
"id": "LB4MtAqOSupA"
},
"execution_count": 3,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"# Defining functions for retrieving/preprocessing text from PDF"
],
"metadata": {
"id": "Lm_D9hkDTtOU"
}
},
{
"cell_type": "code",
"source": [
"def prettify_summary(summary):\n",
" \"\"\"Prettifies the summary.\"\"\"\n",
" # Spliting input into sentences and capitalizing each one\n",
" sentences = sent_tokenize(summary)\n",
" prettified_summary = \" \".join(s.capitalize() for s in sentences)\n",
"\n",
" # Removing unwanted spaces before punctuation\n",
" prettified_summary = re.sub(r'\\s+([.,!?])', r'\\1', prettified_summary)\n",
"\n",
" return prettified_summary"
],
"metadata": {
"id": "jIACNyS_Sum_"
},
"execution_count": 4,
"outputs": []
},
{
"cell_type": "code",
"source": [
"def summarize_text(\n",
" model,\n",
" tokenizer,\n",
" text,\n",
" device=\"cuda\",\n",
" max_input_length=1024,\n",
" max_output_length=250,\n",
"):\n",
" \"\"\"Tokenizes and generates a summary based on input text.\"\"\"\n",
" inputs = tokenizer(\n",
" text,\n",
" return_tensors=\"pt\",\n",
" truncation=True,\n",
" max_length=max_input_length\n",
" ).to(device)\n",
"\n",
" summary_ids = model.generate(\n",
" **inputs,\n",
" max_length=max_output_length,\n",
" num_beams=4,\n",
" early_stopping=True\n",
" )\n",
"\n",
" # Decoding and prettifying output\n",
" raw_summary = tokenizer.decode(summary_ids[0], skip_special_tokens=True)\n",
"\n",
" return prettify_summary(raw_summary)"
],
"metadata": {
"id": "rwdQqpxySuki"
},
"execution_count": 5,
"outputs": []
},
{
"cell_type": "code",
"source": [
"def extract_main_text(pdf_path: str, beginning=\"introduction\") -> str:\n",
" \"\"\"Retrieves the article text after abstract and before references.\n",
"\n",
" Args:\n",
" pdf_path (str): Path to the pdf-file with the article.\n",
" beginning (str, optional): The beginning from which to start retrieving text.\n",
" Defaults to \"introduction\".\n",
" Returns:\n",
" str: Extracted text.\n",
" \"\"\"\n",
" # Extracting text from each page\n",
" doc = fitz.open(pdf_path)\n",
" full_text = \"\"\n",
" for page in doc:\n",
" full_text += page.get_text(\"text\") + \"\\n\"\n",
"\n",
" # Finding the start of the main text (after Abstract)\n",
" abstract_end_idx = full_text.lower().find(beginning) + len(beginning)\n",
" if abstract_end_idx == -1: # If \"Introduction\" not found, falling back to first line after \"Abstract\"\n",
" abstract_end_idx = full_text.lower().find(\"abstract\") + len(\"abstract\")\n",
"\n",
" # Finding the end of the main text (before References)\n",
" references_idx = full_text.lower().find(\"references\")\n",
" if references_idx == -1: # If \"References\" section not found, extracting till the end\n",
" references_idx = len(full_text)\n",
"\n",
" # Extract only the part between Abstract and References\n",
" main_text = full_text[abstract_end_idx:references_idx].strip()\n",
" return main_text"
],
"metadata": {
"id": "s8ZbvKaMSuh1"
},
"execution_count": 6,
"outputs": []
},
{
"cell_type": "code",
"source": [
"def clean_text(text):\n",
" \"\"\"Cleans the extracted paper text.\"\"\"\n",
" text = re.sub(r'\\s+', ' ', text)\n",
"\n",
" return text.strip()"
],
"metadata": {
"id": "001u8wp8S1Zh"
},
"execution_count": 7,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"# Generating summaries on sample articles"
],
"metadata": {
"id": "HwDjXitFT1ta"
}
},
{
"cell_type": "markdown",
"source": [
"**NOTE:** *In order to test the summarization models one needs to firstly download the articles in pdf and upload to Google Colab*:\n",
"\n",
"* [Efficient Estimation of Word Representations in Vector Space](https://arxiv.org/abs/1301.3781)\n",
"* [Attention Is All You Need](https://arxiv.org/abs/1706.03762)\n",
"* [Recurrent Neural Networks (RNNs): A gentle Introduction and Overview](https://arxiv.org/abs/1912.05911)"
],
"metadata": {
"id": "CMBfxKkVkKBj"
}
},
{
"cell_type": "markdown",
"source": [
"## Article 1: [Efficient Estimation of Word Representations in Vector Space](https://arxiv.org/abs/1301.3781)"
],
"metadata": {
"id": "cOlVk8OyT5eO"
}
},
{
"cell_type": "markdown",
"source": [
"### Retrieving article text"
],
"metadata": {
"id": "RH-HLD1eXU2w"
}
},
{
"cell_type": "code",
"source": [
"article_pdf_path_1 = \"/content/1301.3781v3.pdf\""
],
"metadata": {
"id": "w3H7a1m0hO9z"
},
"execution_count": 8,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Example usage\n",
"article_text = extract_main_text(pdf_path=article_pdf_path_1, beginning=\"introduction\")\n",
"article_text_cleaned = clean_text(article_text)\n",
"article_text_cleaned[:1000]"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 139
},
"id": "Pgb4GhWSm9KL",
"outputId": "42b6003a-3fe2-4871-f799-007b1b8a886a"
},
"execution_count": 9,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Many current NLP systems and techniques treat words as atomic units - there is no notion of similar- ity between words, as these are represented as indices in a vocabulary. This choice has several good reasons - simplicity, robustness and the observation that simple models trained on huge amounts of data outperform complex systems trained on less data. An example is the popular N-gram model used for statistical language modeling - today, it is possible to train N-grams on virtually all available data (trillions of words [3]). However, the simple techniques are at their limits in many tasks. For example, the amount of relevant in-domain data for automatic speech recognition is limited - the performance is usually dominated by the size of high quality transcribed speech data (often just millions of words). In machine translation, the existing corpora for many languages contain only a few billions of words or less. Thus, there are situations where simple scaling up of the basic techniques'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 9
}
]
},
{
"cell_type": "markdown",
"source": [
"### Generating summaries"
],
"metadata": {
"id": "JJ7r-WOCXZ3y"
}
},
{
"cell_type": "code",
"source": [
"lora_summary = summarize_text(model=lora_model.to(\"cuda\"), tokenizer=tokenizer, text=article_text_cleaned)\n",
"lora_summary"
],
"metadata": {
"id": "q8-6eVcsS6H0",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 104
},
"outputId": "ffeafb71-ea36-43fb-b2bf-9551d4ffa7ff"
},
"execution_count": 10,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'We develop new techniques for learning high-quality word vectors from huge data sets with billions of words, and with millions of words in the vocabulary. We use recently proposed techniques for measuring the quality of the resulting vector representa- tions, with the expectation that not only will similar words tend to be close to each other, but that words can have multiple degrees of similarity. We design a new comprehensive test set for measuring both syntactic and semantic regularities1, and show that many such regularities can be learned with high accuracy. We discuss how training time and accuracy depends on the dimensionality of the word vectors and on the amount of the training data.'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 10
}
]
},
{
"cell_type": "code",
"source": [
"original_summary = summarize_text(model=original_model.to(\"cuda\"), tokenizer=tokenizer, text=article_text_cleaned)\n",
"original_summary"
],
"metadata": {
"id": "IbLkYIRVS6Fu",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 87
},
"outputId": "f5ba105d-cff8-43fc-e6e6-9aa090f714ec"
},
"execution_count": 11,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Many current nlp systems and techniques treat words as atomic units - there is no notion of similar- ity between words. This choice has several good reasons - simplicity, robustness and the observation that simple models trained on huge amounts of data outperform complex systems trained on less data. The main goal of this paper is to introduce techniques that can be used for learning high-quality word vectors from huge data sets with billions of words.'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 11
}
]
},
{
"cell_type": "markdown",
"source": [
"## Article 2: [Attention Is All You Need](https://arxiv.org/abs/1706.03762)"
],
"metadata": {
"id": "w-FlJMTlT8cy"
}
},
{
"cell_type": "code",
"source": [
"article_pdf_path_2 = \"/content/1706.03762v7.pdf\""
],
"metadata": {
"id": "8RCD2sWChM-g"
},
"execution_count": 12,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Example usage\n",
"article_text = extract_main_text(article_pdf_path_2)\n",
"article_text_cleaned = clean_text(article_text)\n",
"article_text_cleaned[:1000]"
],
"metadata": {
"id": "7f54JBALonIT",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 139
},
"outputId": "4007007f-9ec2-461e-94ec-778a8732f239"
},
"execution_count": 13,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Recurrent neural networks, long short-term memory [13] and gated recurrent [7] neural networks in particular, have been firmly established as state of the art approaches in sequence modeling and transduction problems such as language modeling and machine translation [35, 2, 5]. Numerous efforts have since continued to push the boundaries of recurrent language models and encoder-decoder architectures [38, 24, 15]. Recurrent models typically factor computation along the symbol positions of the input and output sequences. Aligning the positions to steps in computation time, they generate a sequence of hidden states ht, as a function of the previous hidden state ht−1 and the input for position t. This inherently sequential nature precludes parallelization within training examples, which becomes critical at longer sequence lengths, as memory constraints limit batching across examples. Recent work has achieved significant improvements in computational efficiency through factorization tricks '"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 13
}
]
},
{
"cell_type": "code",
"source": [
"lora_summary = summarize_text(model=lora_model.to(\"cuda\"), tokenizer=tokenizer, text=article_text_cleaned)\n",
"lora_summary"
],
"metadata": {
"id": "0ac3VOgvT-AN",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 104
},
"outputId": "d318c5b1-dc39-492e-d04c-f99c41e817ca"
},
"execution_count": 14,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'The transformer is the first transduction model relying entirely on self-attention to compute representations of its input and output without using sequence- aligned rnns or convolutional neural networks as basic building block, computing hidden representations in parallel for all input andoutput positions. The transformer allows for significantly more parallelization and can reach a new state of the art in translation quality after being trained for as little as twelve hours on eight p100 gpus. In the following sections, we describe the model architecture, motivate selfattention and discuss its advantages over models such as [17, 18] and convs2s [9].'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 14
}
]
},
{
"cell_type": "code",
"source": [
"original_summary = summarize_text(model=original_model.to(\"cuda\"), tokenizer=tokenizer, text=article_text_cleaned)\n",
"original_summary"
],
"metadata": {
"id": "DrFG4oJVT993",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 87
},
"outputId": "85727c11-441e-45c1-e70e-cc76d60e1cd8"
},
"execution_count": 15,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Recurrent neural networks, long short-term memory [13] and gated recurrent [7] neural networks have been firmly established as state of the art approaches in sequence modeling and transduction problems. In this work we propose the transformer, a model architecture eschewing recurrence and relying entirely on an attention mechanism to draw global dependencies between input and output. The transformer allows for significantly more parallelization and can reach a new state-of-the-art in translation quality after being trained for as little as twelve hours on eight p100 gpus.'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 15
}
]
},
{
"cell_type": "markdown",
"source": [
"## Article 3: [Recurrent Neural Networks (RNNs): A gentle Introduction and Overview](https://arxiv.org/abs/1912.05911)"
],
"metadata": {
"id": "lVcXPuUYT-aR"
}
},
{
"cell_type": "code",
"source": [
"article_pdf_path_3 = \"/content/1912.05911v1.pdf\""
],
"metadata": {
"id": "gjeMgg4ahbzk"
},
"execution_count": 16,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Example usage\n",
"article_text = extract_main_text(pdf_path=article_pdf_path_3, beginning=\"introduction & notation\")\n",
"article_text_cleaned = clean_text(article_text)\n",
"article_text_cleaned[:1000]"
],
"metadata": {
"id": "iedhi7XyUAGP",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 139
},
"outputId": "b97fa906-5da3-469a-af59-b507b1182266"
},
"execution_count": 17,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Recurrent Neural Networks (RNNs) are a type of neural network architecture which is mainly used to detect patterns in a sequence of data. Such data can be handwriting, genomes, text or numerical time series which are often produced in industry settings (e.g. stock markets or sensors) [7, 12]. However, they are also applicable to images if these get respectively decomposed into a series of patches and treated as a sequence [12]. On a higher level, RNNs find applications in Language Modelling & Generating Text, Speech Recognition, Generating Image Descriptions or Video Tagging. What differentiates Recurrent Neural Networks from Feedforward Neural Networks also known as Multi-Layer Perceptrons (MLPs) is how information gets passed through the network. While Feedforward Networks pass information through the network without cycles, the RNN has cycles and transmits information back into itself. This enables them to extend the functionality of Feedforward Networks to also take into account pre'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 17
}
]
},
{
"cell_type": "code",
"source": [
"lora_summary = summarize_text(model=lora_model.to(\"cuda\"), tokenizer=tokenizer, text=article_text_cleaned)\n",
"lora_summary"
],
"metadata": {
"id": "zdAHolweUABG",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 104
},
"outputId": "4db40a39-0da8-473b-bb07-383b8cfa4739"
},
"execution_count": 18,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Recurrent neural networks (rnns) are a type of neural network architecture which is mainly used to detect patterns in a sequence of data such as handwriting, genomes, text or numerical time series. While feedforward networks pass information through the network without cycles, the rnn has cycles and transmits information back into itself. This enables them to extend the functionality of feedforward neural networks to also take into account previous inputs x0:t−1 and not only the current input xt. In this paper, we show how to construct a recurrent neural network using the backpropagation through time (bptt) and truncated bptt algorithm for rnns.'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 18
}
]
},
{
"cell_type": "code",
"source": [
"original_summary = summarize_text(model=original_model.to(\"cuda\"), tokenizer=tokenizer, text=article_text_cleaned)\n",
"original_summary"
],
"metadata": {
"id": "f0CwXPt8T__N",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 70
},
"outputId": "e57dc83f-b3a3-4b22-dccd-a5e2edf1f416"
},
"execution_count": 19,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Recurrent neural networks (rnns) are a type of neural network architecture. They are mainly used to detect patterns in a sequence of data. Rnns have applications in language modelling & generating text, speech recognition, generating image descriptions or video tagging. Backpropagation through time (bptt) is used to backpropagate the error through a rnn.'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 19
}
]
}
]
} |