{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "673acfe6", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/Users/manasvi/Github/RAG-Pipeline/.venv/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n", " from .autonotebook import tqdm as notebook_tqdm\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Found 2 PDF files to process\n", "\n", "Processing: NIPS-2017-attention-is-all-you-need-Paper.pdf\n", " ✓ Loaded 11 pages\n", "\n", "Processing: 2310.05421v1.pdf\n", " ✓ Loaded 4 pages\n", "\n", "Total documents loaded: 15\n" ] } ], "source": [ "import os\n", "from langchain_community.document_loaders import PyPDFLoader, PyMuPDFLoader\n", "from langchain_text_splitters import RecursiveCharacterTextSplitter\n", "from pathlib import Path\n", "### Read all the pdf's inside the directory\n", "def process_all_pdfs(pdf_directory):\n", " \"\"\"Process all PDF files in a directory\"\"\"\n", " all_documents = []\n", " pdf_dir = Path(pdf_directory)\n", " \n", " # Find all PDF files recursively\n", " pdf_files = list(pdf_dir.glob(\"**/*.pdf\"))\n", " \n", " print(f\"Found {len(pdf_files)} PDF files to process\")\n", " \n", " for pdf_file in pdf_files:\n", " print(f\"\\nProcessing: {pdf_file.name}\")\n", " try:\n", " loader = PyPDFLoader(str(pdf_file))\n", " documents = loader.load()\n", " \n", " # Add source information to metadata\n", " for doc in documents:\n", " doc.metadata['source_file'] = pdf_file.name\n", " doc.metadata['file_type'] = 'pdf'\n", " \n", " all_documents.extend(documents)\n", " print(f\" ✓ Loaded {len(documents)} pages\")\n", " \n", " except Exception as e:\n", " print(f\" ✗ Error: {e}\")\n", " \n", " print(f\"\\nTotal documents loaded: {len(all_documents)}\")\n", " return all_documents\n", "\n", "# Process all PDFs in the data directory\n", "all_pdf_documents = process_all_pdfs(\"../data/pdf\")" ] }, { "cell_type": "code", "execution_count": 2, "id": "3c788874", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Split 15 documents into 62 chunks\n", "\n", "Example chunk:\n", "Content: Attention Is All You Need\n", "Ashish Vaswani∗\n", "Google Brain\n", "avaswani@google.com\n", "Noam Shazeer∗\n", "Google Brain\n", "noam@google.com\n", "Niki Parmar∗\n", "Google Research\n", "nikip@google.com\n", "Jakob Uszkoreit∗\n", "Google Research\n", "usz...\n", "Metadata: {'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 0, 'page_label': '1', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}\n" ] }, { "data": { "text/plain": [ "[Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 0, 'page_label': '1', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='Attention Is All You Need\\nAshish Vaswani∗\\nGoogle Brain\\navaswani@google.com\\nNoam Shazeer∗\\nGoogle Brain\\nnoam@google.com\\nNiki Parmar∗\\nGoogle Research\\nnikip@google.com\\nJakob Uszkoreit∗\\nGoogle Research\\nusz@google.com\\nLlion Jones∗\\nGoogle Research\\nllion@google.com\\nAidan N. Gomez∗†\\nUniversity of Toronto\\naidan@cs.toronto.edu\\nŁukasz Kaiser ∗\\nGoogle Brain\\nlukaszkaiser@google.com\\nIllia Polosukhin∗‡\\nillia.polosukhin@gmail.com\\nAbstract\\nThe dominant sequence transduction models are based on complex recurrent or\\nconvolutional neural networks that include an encoder and a decoder. The best\\nperforming models also connect the encoder and decoder through an attention\\nmechanism. We propose a new simple network architecture, the Transformer,\\nbased solely on attention mechanisms, dispensing with recurrence and convolutions\\nentirely. Experiments on two machine translation tasks show these models to\\nbe superior in quality while being more parallelizable and requiring significantly'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 0, 'page_label': '1', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='entirely. Experiments on two machine translation tasks show these models to\\nbe superior in quality while being more parallelizable and requiring significantly\\nless time to train. Our model achieves 28.4 BLEU on the WMT 2014 English-\\nto-German translation task, improving over the existing best results, including\\nensembles, by over 2 BLEU. On the WMT 2014 English-to-French translation task,\\nour model establishes a new single-model state-of-the-art BLEU score of 41.0 after\\ntraining for 3.5 days on eight GPUs, a small fraction of the training costs of the\\nbest models from the literature.\\n1 Introduction\\nRecurrent neural networks, long short-term memory [12] and gated recurrent [7] neural networks\\nin particular, have been firmly established as state of the art approaches in sequence modeling and\\ntransduction problems such as language modeling and machine translation [ 29, 2, 5]. Numerous\\nefforts have since continued to push the boundaries of recurrent language models and encoder-decoder'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 0, 'page_label': '1', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='transduction problems such as language modeling and machine translation [ 29, 2, 5]. Numerous\\nefforts have since continued to push the boundaries of recurrent language models and encoder-decoder\\narchitectures [31, 21, 13].\\n∗Equal contribution. Listing order is random. Jakob proposed replacing RNNs with self-attention and started\\nthe effort to evaluate this idea. Ashish, with Illia, designed and implemented the first Transformer models and\\nhas been crucially involved in every aspect of this work. Noam proposed scaled dot-product attention, multi-head\\nattention and the parameter-free position representation and became the other person involved in nearly every\\ndetail. Niki designed, implemented, tuned and evaluated countless model variants in our original codebase and\\ntensor2tensor. Llion also experimented with novel model variants, was responsible for our initial codebase, and\\nefficient inference and visualizations. Lukasz and Aidan spent countless long days designing various parts of and'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 0, 'page_label': '1', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='efficient inference and visualizations. Lukasz and Aidan spent countless long days designing various parts of and\\nimplementing tensor2tensor, replacing our earlier codebase, greatly improving results and massively accelerating\\nour research.\\n†Work performed while at Google Brain.\\n‡Work performed while at Google Research.\\n31st Conference on Neural Information Processing Systems (NIPS 2017), Long Beach, CA, USA.'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 1, 'page_label': '2', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='Recurrent models typically factor computation along the symbol positions of the input and output\\nsequences. Aligning the positions to steps in computation time, they generate a sequence of hidden\\nstates ht, as a function of the previous hidden state ht−1 and the input for position t. This inherently\\nsequential nature precludes parallelization within training examples, which becomes critical at longer\\nsequence lengths, as memory constraints limit batching across examples. Recent work has achieved\\nsignificant improvements in computational efficiency through factorization tricks [18] and conditional\\ncomputation [26], while also improving model performance in case of the latter. The fundamental\\nconstraint of sequential computation, however, remains.\\nAttention mechanisms have become an integral part of compelling sequence modeling and transduc-\\ntion models in various tasks, allowing modeling of dependencies without regard to their distance in'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 1, 'page_label': '2', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='Attention mechanisms have become an integral part of compelling sequence modeling and transduc-\\ntion models in various tasks, allowing modeling of dependencies without regard to their distance in\\nthe input or output sequences [2, 16]. In all but a few cases [22], however, such attention mechanisms\\nare used in conjunction with a recurrent network.\\nIn this work we propose the Transformer, a model architecture eschewing recurrence and instead\\nrelying entirely on an attention mechanism to draw global dependencies between input and output.\\nThe Transformer allows for significantly more parallelization and can reach a new state of the art in\\ntranslation quality after being trained for as little as twelve hours on eight P100 GPUs.\\n2 Background\\nThe goal of reducing sequential computation also forms the foundation of the Extended Neural GPU\\n[20], ByteNet [15] and ConvS2S [8], all of which use convolutional neural networks as basic building'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 1, 'page_label': '2', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='The goal of reducing sequential computation also forms the foundation of the Extended Neural GPU\\n[20], ByteNet [15] and ConvS2S [8], all of which use convolutional neural networks as basic building\\nblock, computing hidden representations in parallel for all input and output positions. In these models,\\nthe number of operations required to relate signals from two arbitrary input or output positions grows\\nin the distance between positions, linearly for ConvS2S and logarithmically for ByteNet. This makes\\nit more difficult to learn dependencies between distant positions [ 11]. In the Transformer this is\\nreduced to a constant number of operations, albeit at the cost of reduced effective resolution due\\nto averaging attention-weighted positions, an effect we counteract with Multi-Head Attention as\\ndescribed in section 3.2.\\nSelf-attention, sometimes called intra-attention is an attention mechanism relating different positions'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 1, 'page_label': '2', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='described in section 3.2.\\nSelf-attention, sometimes called intra-attention is an attention mechanism relating different positions\\nof a single sequence in order to compute a representation of the sequence. Self-attention has been\\nused successfully in a variety of tasks including reading comprehension, abstractive summarization,\\ntextual entailment and learning task-independent sentence representations [4, 22, 23, 19].\\nEnd-to-end memory networks are based on a recurrent attention mechanism instead of sequence-\\naligned recurrence and have been shown to perform well on simple-language question answering and\\nlanguage modeling tasks [28].\\nTo the best of our knowledge, however, the Transformer is the first transduction model relying\\nentirely on self-attention to compute representations of its input and output without using sequence-\\naligned RNNs or convolution. In the following sections, we will describe the Transformer, motivate'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 1, 'page_label': '2', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='aligned RNNs or convolution. In the following sections, we will describe the Transformer, motivate\\nself-attention and discuss its advantages over models such as [14, 15] and [8].\\n3 Model Architecture\\nMost competitive neural sequence transduction models have an encoder-decoder structure [5, 2, 29].\\nHere, the encoder maps an input sequence of symbol representations (x1,...,x n) to a sequence\\nof continuous representations z = (z1,...,z n). Given z, the decoder then generates an output\\nsequence (y1,...,y m) of symbols one element at a time. At each step the model is auto-regressive\\n[9], consuming the previously generated symbols as additional input when generating the next.\\nThe Transformer follows this overall architecture using stacked self-attention and point-wise, fully\\nconnected layers for both the encoder and decoder, shown in the left and right halves of Figure 1,\\nrespectively.\\n3.1 Encoder and Decoder Stacks'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 1, 'page_label': '2', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='connected layers for both the encoder and decoder, shown in the left and right halves of Figure 1,\\nrespectively.\\n3.1 Encoder and Decoder Stacks\\nEncoder: The encoder is composed of a stack of N = 6 identical layers. Each layer has two\\nsub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, position-\\n2'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 2, 'page_label': '3', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='Figure 1: The Transformer - model architecture.\\nwise fully connected feed-forward network. We employ a residual connection [10] around each of\\nthe two sub-layers, followed by layer normalization [ 1]. That is, the output of each sub-layer is\\nLayerNorm(x+ Sublayer(x)), where Sublayer(x) is the function implemented by the sub-layer\\nitself. To facilitate these residual connections, all sub-layers in the model, as well as the embedding\\nlayers, produce outputs of dimension dmodel = 512.\\nDecoder: The decoder is also composed of a stack of N = 6identical layers. In addition to the two\\nsub-layers in each encoder layer, the decoder inserts a third sub-layer, which performs multi-head\\nattention over the output of the encoder stack. Similar to the encoder, we employ residual connections\\naround each of the sub-layers, followed by layer normalization. We also modify the self-attention\\nsub-layer in the decoder stack to prevent positions from attending to subsequent positions. This'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 2, 'page_label': '3', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='around each of the sub-layers, followed by layer normalization. We also modify the self-attention\\nsub-layer in the decoder stack to prevent positions from attending to subsequent positions. This\\nmasking, combined with fact that the output embeddings are offset by one position, ensures that the\\npredictions for position ican depend only on the known outputs at positions less than i.\\n3.2 Attention\\nAn attention function can be described as mapping a query and a set of key-value pairs to an output,\\nwhere the query, keys, values, and output are all vectors. The output is computed as a weighted sum\\nof the values, where the weight assigned to each value is computed by a compatibility function of the\\nquery with the corresponding key.\\n3.2.1 Scaled Dot-Product Attention\\nWe call our particular attention \"Scaled Dot-Product Attention\" (Figure 2). The input consists of\\nqueries and keys of dimension dk, and values of dimension dv. We compute the dot products of the\\n3'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 3, 'page_label': '4', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='Scaled Dot-Product Attention\\n Multi-Head Attention\\nFigure 2: (left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several\\nattention layers running in parallel.\\nquery with all keys, divide each by √dk, and apply a softmax function to obtain the weights on the\\nvalues.\\nIn practice, we compute the attention function on a set of queries simultaneously, packed together\\ninto a matrix Q. The keys and values are also packed together into matrices Kand V. We compute\\nthe matrix of outputs as:\\nAttention(Q,K,V ) = softmax(QKT\\n√dk\\n)V (1)\\nThe two most commonly used attention functions are additive attention [2], and dot-product (multi-\\nplicative) attention. Dot-product attention is identical to our algorithm, except for the scaling factor\\nof 1√dk\\n. Additive attention computes the compatibility function using a feed-forward network with\\na single hidden layer. While the two are similar in theoretical complexity, dot-product attention is'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 3, 'page_label': '4', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='of 1√dk\\n. Additive attention computes the compatibility function using a feed-forward network with\\na single hidden layer. While the two are similar in theoretical complexity, dot-product attention is\\nmuch faster and more space-efficient in practice, since it can be implemented using highly optimized\\nmatrix multiplication code.\\nWhile for small values of dk the two mechanisms perform similarly, additive attention outperforms\\ndot product attention without scaling for larger values of dk [3]. We suspect that for large values of\\ndk, the dot products grow large in magnitude, pushing the softmax function into regions where it has\\nextremely small gradients 4. To counteract this effect, we scale the dot products by 1√dk\\n.\\n3.2.2 Multi-Head Attention\\nInstead of performing a single attention function with dmodel-dimensional keys, values and queries,\\nwe found it beneficial to linearly project the queries, keys and values htimes with different, learned'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 3, 'page_label': '4', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='we found it beneficial to linearly project the queries, keys and values htimes with different, learned\\nlinear projections to dk, dk and dv dimensions, respectively. On each of these projected versions of\\nqueries, keys and values we then perform the attention function in parallel, yielding dv-dimensional\\noutput values. These are concatenated and once again projected, resulting in the final values, as\\ndepicted in Figure 2.\\nMulti-head attention allows the model to jointly attend to information from different representation\\nsubspaces at different positions. With a single attention head, averaging inhibits this.\\n4To illustrate why the dot products get large, assume that the components of q and k are independent random\\nvariables with mean 0 and variance 1. Then their dot product, q · k = ∑dk\\ni=1 qiki, has mean 0 and variance dk.\\n4'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 4, 'page_label': '5', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='MultiHead(Q,K,V ) = Concat(head1,..., headh)WO\\nwhere headi = Attention(QWQ\\ni ,KW K\\ni ,VW V\\ni )\\nWhere the projections are parameter matricesWQ\\ni ∈Rdmodel×dk , WK\\ni ∈Rdmodel×dk , WV\\ni ∈Rdmodel×dv\\nand WO ∈Rhdv×dmodel .\\nIn this work we employ h = 8 parallel attention layers, or heads. For each of these we use\\ndk = dv = dmodel/h= 64. Due to the reduced dimension of each head, the total computational cost\\nis similar to that of single-head attention with full dimensionality.\\n3.2.3 Applications of Attention in our Model\\nThe Transformer uses multi-head attention in three different ways:\\n• In \"encoder-decoder attention\" layers, the queries come from the previous decoder layer,\\nand the memory keys and values come from the output of the encoder. This allows every\\nposition in the decoder to attend over all positions in the input sequence. This mimics the\\ntypical encoder-decoder attention mechanisms in sequence-to-sequence models such as\\n[31, 2, 8].'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 4, 'page_label': '5', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='position in the decoder to attend over all positions in the input sequence. This mimics the\\ntypical encoder-decoder attention mechanisms in sequence-to-sequence models such as\\n[31, 2, 8].\\n• The encoder contains self-attention layers. In a self-attention layer all of the keys, values\\nand queries come from the same place, in this case, the output of the previous layer in the\\nencoder. Each position in the encoder can attend to all positions in the previous layer of the\\nencoder.\\n• Similarly, self-attention layers in the decoder allow each position in the decoder to attend to\\nall positions in the decoder up to and including that position. We need to prevent leftward\\ninformation flow in the decoder to preserve the auto-regressive property. We implement this\\ninside of scaled dot-product attention by masking out (setting to −∞) all values in the input\\nof the softmax which correspond to illegal connections. See Figure 2.\\n3.3 Position-wise Feed-Forward Networks'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 4, 'page_label': '5', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='of the softmax which correspond to illegal connections. See Figure 2.\\n3.3 Position-wise Feed-Forward Networks\\nIn addition to attention sub-layers, each of the layers in our encoder and decoder contains a fully\\nconnected feed-forward network, which is applied to each position separately and identically. This\\nconsists of two linear transformations with a ReLU activation in between.\\nFFN(x) = max(0,xW1 + b1)W2 + b2 (2)\\nWhile the linear transformations are the same across different positions, they use different parameters\\nfrom layer to layer. Another way of describing this is as two convolutions with kernel size 1.\\nThe dimensionality of input and output is dmodel = 512, and the inner-layer has dimensionality\\ndff = 2048.\\n3.4 Embeddings and Softmax\\nSimilarly to other sequence transduction models, we use learned embeddings to convert the input\\ntokens and output tokens to vectors of dimension dmodel. We also use the usual learned linear transfor-'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 4, 'page_label': '5', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='Similarly to other sequence transduction models, we use learned embeddings to convert the input\\ntokens and output tokens to vectors of dimension dmodel. We also use the usual learned linear transfor-\\nmation and softmax function to convert the decoder output to predicted next-token probabilities. In\\nour model, we share the same weight matrix between the two embedding layers and the pre-softmax\\nlinear transformation, similar to [24]. In the embedding layers, we multiply those weights by √dmodel.\\n3.5 Positional Encoding\\nSince our model contains no recurrence and no convolution, in order for the model to make use of the\\norder of the sequence, we must inject some information about the relative or absolute position of the\\ntokens in the sequence. To this end, we add \"positional encodings\" to the input embeddings at the\\n5'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 5, 'page_label': '6', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='Table 1: Maximum path lengths, per-layer complexity and minimum number of sequential operations\\nfor different layer types. nis the sequence length, dis the representation dimension, kis the kernel\\nsize of convolutions and rthe size of the neighborhood in restricted self-attention.\\nLayer Type Complexity per Layer Sequential Maximum Path Length\\nOperations\\nSelf-Attention O(n2 ·d) O(1) O(1)\\nRecurrent O(n·d2) O(n) O(n)\\nConvolutional O(k·n·d2) O(1) O(logk(n))\\nSelf-Attention (restricted) O(r·n·d) O(1) O(n/r)\\nbottoms of the encoder and decoder stacks. The positional encodings have the same dimension dmodel\\nas the embeddings, so that the two can be summed. There are many choices of positional encodings,\\nlearned and fixed [8].\\nIn this work, we use sine and cosine functions of different frequencies:\\nPE(pos,2i) = sin(pos/100002i/dmodel )\\nPE(pos,2i+1) = cos(pos/100002i/dmodel )\\nwhere posis the position and iis the dimension. That is, each dimension of the positional encoding'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 5, 'page_label': '6', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='PE(pos,2i) = sin(pos/100002i/dmodel )\\nPE(pos,2i+1) = cos(pos/100002i/dmodel )\\nwhere posis the position and iis the dimension. That is, each dimension of the positional encoding\\ncorresponds to a sinusoid. The wavelengths form a geometric progression from 2πto 10000 ·2π. We\\nchose this function because we hypothesized it would allow the model to easily learn to attend by\\nrelative positions, since for any fixed offset k, PEpos+k can be represented as a linear function of\\nPEpos.\\nWe also experimented with using learned positional embeddings [8] instead, and found that the two\\nversions produced nearly identical results (see Table 3 row (E)). We chose the sinusoidal version\\nbecause it may allow the model to extrapolate to sequence lengths longer than the ones encountered\\nduring training.\\n4 Why Self-Attention\\nIn this section we compare various aspects of self-attention layers to the recurrent and convolu-'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 5, 'page_label': '6', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='during training.\\n4 Why Self-Attention\\nIn this section we compare various aspects of self-attention layers to the recurrent and convolu-\\ntional layers commonly used for mapping one variable-length sequence of symbol representations\\n(x1,...,x n) to another sequence of equal length (z1,...,z n), with xi,zi ∈Rd, such as a hidden\\nlayer in a typical sequence transduction encoder or decoder. Motivating our use of self-attention we\\nconsider three desiderata.\\nOne is the total computational complexity per layer. Another is the amount of computation that can\\nbe parallelized, as measured by the minimum number of sequential operations required.\\nThe third is the path length between long-range dependencies in the network. Learning long-range\\ndependencies is a key challenge in many sequence transduction tasks. One key factor affecting the\\nability to learn such dependencies is the length of the paths forward and backward signals have to'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 5, 'page_label': '6', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='dependencies is a key challenge in many sequence transduction tasks. One key factor affecting the\\nability to learn such dependencies is the length of the paths forward and backward signals have to\\ntraverse in the network. The shorter these paths between any combination of positions in the input\\nand output sequences, the easier it is to learn long-range dependencies [11]. Hence we also compare\\nthe maximum path length between any two input and output positions in networks composed of the\\ndifferent layer types.\\nAs noted in Table 1, a self-attention layer connects all positions with a constant number of sequentially\\nexecuted operations, whereas a recurrent layer requires O(n) sequential operations. In terms of\\ncomputational complexity, self-attention layers are faster than recurrent layers when the sequence\\nlength n is smaller than the representation dimensionality d, which is most often the case with'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 5, 'page_label': '6', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='computational complexity, self-attention layers are faster than recurrent layers when the sequence\\nlength n is smaller than the representation dimensionality d, which is most often the case with\\nsentence representations used by state-of-the-art models in machine translations, such as word-piece\\n[31] and byte-pair [25] representations. To improve computational performance for tasks involving\\nvery long sequences, self-attention could be restricted to considering only a neighborhood of size rin\\n6'),\n", " Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms. We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'page': 6, 'page_label': '7', 'source_file': 'NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_type': 'pdf'}, page_content='the input sequence centered around the respective output position. This would increase the maximum\\npath length to O(n/r). We plan to investigate this approach further in future work.\\nA single convolutional layer with kernel width k" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import numpy as np\n", "from sentence_transformers import SentenceTransformer\n", "import chromadb\n", "from chromadb.config import Settings\n", "import uuid\n", "from typing import List, Dict, Any, Tuple\n", "from sklearn.metrics.pairwise import cosine_similarity\n", "\n", "class EmbeddingManager:\n", " \"\"\"Handles document embedding generation using SentenceTransformer\"\"\"\n", " \n", " def __init__(self, model_name: str = \"all-MiniLM-L6-v2\"):\n", " \"\"\"\n", " Initialize the embedding manager\n", " \n", " Args:\n", " model_name: HuggingFace model name for sentence embeddings\n", " \"\"\"\n", " self.model_name = model_name\n", " self.model = None\n", " self._load_model()\n", "\n", " def _load_model(self):\n", " \"\"\"Load the SentenceTransformer model\"\"\"\n", " try:\n", " print(f\"Loading embedding model: {self.model_name}\")\n", " self.model = SentenceTransformer(self.model_name)\n", " print(f\"Model loaded successfully. Embedding dimension: {self.model.get_sentence_embedding_dimension()}\")\n", " except Exception as e:\n", " print(f\"Error loading model {self.model_name}: {e}\")\n", " raise\n", "\n", " def generate_embeddings(self, texts: List[str]) -> np.ndarray:\n", " \"\"\"\n", " Generate embeddings for a list of texts\n", " \n", " Args:\n", " texts: List of text strings to embed\n", " \n", " Returns:\n", " numpy array of embeddings with shape (len(texts), embedding_dim)\n", " \"\"\"\n", " if not self.model:\n", " raise ValueError(\"Model not loaded\")\n", " \n", " print(f\"Generating embeddings for {len(texts)} texts...\")\n", " embeddings = self.model.encode(texts, show_progress_bar=True)\n", " print(f\"Generated embeddings with shape: {embeddings.shape}\")\n", " return embeddings\n", "\n", "\n", "## initialize the embedding manager\n", "\n", "embedding_manager=EmbeddingManager()\n", "embedding_manager" ] }, { "cell_type": "code", "execution_count": 4, "id": "9f36ff98", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Vector store initialized. Collection: pdf_documents\n", "Existing documents in collection: 124\n" ] }, { "data": { "text/plain": [ "<__main__.VectorStore at 0x13e7c7350>" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "class VectorStore:\n", " \"\"\"Manages document embeddings in a ChromaDB vector store\"\"\"\n", " \n", " def __init__(self, collection_name: str = \"pdf_documents\", persist_directory: str = \"../data/vector_store\"):\n", " \"\"\"\n", " Initialize the vector store\n", " \n", " Args:\n", " collection_name: Name of the ChromaDB collection\n", " persist_directory: Directory to persist the vector store\n", " \"\"\"\n", " self.collection_name = collection_name\n", " self.persist_directory = persist_directory\n", " self.client = None\n", " self.collection = None\n", " self._initialize_store()\n", "\n", " def _initialize_store(self):\n", " \"\"\"Initialize ChromaDB client and collection\"\"\"\n", " try:\n", " # Create persistent ChromaDB client\n", " os.makedirs(self.persist_directory, exist_ok=True)\n", " self.client = chromadb.PersistentClient(path=self.persist_directory)\n", " \n", " # Get or create collection\n", " self.collection = self.client.get_or_create_collection(\n", " name=self.collection_name,\n", " metadata={\"description\": \"PDF document embeddings for RAG\"}\n", " )\n", " print(f\"Vector store initialized. Collection: {self.collection_name}\")\n", " print(f\"Existing documents in collection: {self.collection.count()}\")\n", " \n", " except Exception as e:\n", " print(f\"Error initializing vector store: {e}\")\n", " raise\n", "\n", " def add_documents(self, documents: List[Any], embeddings: np.ndarray):\n", " \"\"\"\n", " Add documents and their embeddings to the vector store\n", " \n", " Args:\n", " documents: List of LangChain documents\n", " embeddings: Corresponding embeddings for the documents\n", " \"\"\"\n", " if len(documents) != len(embeddings):\n", " raise ValueError(\"Number of documents must match number of embeddings\")\n", " \n", " print(f\"Adding {len(documents)} documents to vector store...\")\n", " \n", " # Prepare data for ChromaDB\n", " ids = []\n", " metadatas = []\n", " documents_text = []\n", " embeddings_list = []\n", " \n", " for i, (doc, embedding) in enumerate(zip(documents, embeddings)):\n", " # Generate unique ID\n", " doc_id = f\"doc_{uuid.uuid4().hex[:8]}_{i}\"\n", " ids.append(doc_id)\n", " \n", " # Prepare metadata\n", " metadata = dict(doc.metadata)\n", " metadata['doc_index'] = i\n", " metadata['content_length'] = len(doc.page_content)\n", " metadatas.append(metadata)\n", " # Document content\n", " documents_text.append(doc.page_content)\n", " \n", " # Embedding\n", " embeddings_list.append(embedding.tolist())\n", " \n", " # Add to collection\n", " try:\n", " self.collection.add(\n", " ids=ids,\n", " embeddings=embeddings_list,\n", " metadatas=metadatas,\n", " documents=documents_text\n", " )\n", " print(f\"Successfully added {len(documents)} documents to vector store\")\n", " print(f\"Total documents in collection: {self.collection.count()}\")\n", " \n", " except Exception as e:\n", " print(f\"Error adding documents to vector store: {e}\")\n", " raise\n", "\n", "vectorstore=VectorStore()\n", "vectorstore" ] }, { "cell_type": "code", "execution_count": 5, "id": "a4c2e333", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Generating embeddings for 62 texts...\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Batches: 100%|██████████| 2/2 [00:01<00:00, 1.54it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Generated embeddings with shape: (62, 384)\n", "Adding 62 documents to vector store...\n", "Successfully added 62 documents to vector store\n", "Total documents in collection: 186\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "### Convert the text to embeddings\n", "texts=[doc.page_content for doc in chunks]\n", "\n", "## Generate the Embeddings\n", "\n", "embeddings=embedding_manager.generate_embeddings(texts)\n", "\n", "##store int he vector dtaabase\n", "vectorstore.add_documents(chunks,embeddings)" ] }, { "cell_type": "code", "execution_count": 6, "id": "4c234a53", "metadata": {}, "outputs": [], "source": [ "class RAGRetriever:\n", " \"\"\"Handles query-based retrieval from the vector store\"\"\"\n", " \n", " def __init__(self, vector_store: VectorStore, embedding_manager: EmbeddingManager):\n", " \"\"\"\n", " Initialize the retriever\n", " \n", " Args:\n", " vector_store: Vector store containing document embeddings\n", " embedding_manager: Manager for generating query embeddings\n", " \"\"\"\n", " self.vector_store = vector_store\n", " self.embedding_manager = embedding_manager\n", "\n", " def retrieve(self, query: str, top_k: int = 5, score_threshold: float = 0.0) -> List[Dict[str, Any]]:\n", " \"\"\"\n", " Retrieve relevant documents for a query\n", " \n", " Args:\n", " query: The search query\n", " top_k: Number of top results to return\n", " score_threshold: Minimum similarity score threshold\n", " \n", " Returns:\n", " List of dictionaries containing retrieved documents and metadata\n", " \"\"\"\n", " print(f\"Retrieving documents for query: '{query}'\")\n", " print(f\"Top K: {top_k}, Score threshold: {score_threshold}\")\n", " \n", " # Generate query embedding\n", " query_embedding = self.embedding_manager.generate_embeddings([query])[0]\n", " \n", " # Search in vector store\n", " try:\n", " results = self.vector_store.collection.query(\n", " query_embeddings=[query_embedding.tolist()],\n", " n_results=top_k\n", " )\n", " \n", " # Process results\n", " retrieved_docs = []\n", " \n", " if results['documents'] and results['documents'][0]:\n", " documents = results['documents'][0]\n", " metadatas = results['metadatas'][0]\n", " distances = results['distances'][0]\n", " ids = results['ids'][0]\n", " \n", " for i, (doc_id, document, metadata, distance) in enumerate(zip(ids, documents, metadatas, distances)):\n", " # Convert distance to similarity score (ChromaDB uses cosine distance)\n", " similarity_score = 1 - distance\n", " \n", " if similarity_score >= score_threshold:\n", " retrieved_docs.append({\n", " 'id': doc_id,\n", " 'content': document,\n", " 'metadata': metadata,\n", " 'similarity_score': similarity_score,\n", " 'distance': distance,\n", " 'rank': i + 1\n", " })\n", " \n", " print(f\"Retrieved {len(retrieved_docs)} documents (after filtering)\")\n", " else:\n", " print(\"No documents found\")\n", " \n", " return retrieved_docs\n", " \n", " except Exception as e:\n", " print(f\"Error during retrieval: {e}\")\n", " return []\n", "\n", "rag_retriever=RAGRetriever(vectorstore,embedding_manager)" ] }, { "cell_type": "code", "execution_count": 7, "id": "402e545f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Retrieving documents for query: 'What is attention is all you need'\n", "Top K: 5, Score threshold: 0.0\n", "Generating embeddings for 1 texts...\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Batches: 100%|██████████| 1/1 [00:00<00:00, 1.04it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Generated embeddings with shape: (1, 384)\n", "Retrieved 0 documents (after filtering)\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n" ] }, { "data": { "text/plain": [ "[]" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "rag_retriever.retrieve(\"What is attention is all you need\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "51204a01", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "f04990b7", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "8e8d1c27", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": ".venv", "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.12.7" } }, "nbformat": 4, "nbformat_minor": 5 }