{ "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 } ] } ] }