"## Better retrieval via \"Dense Passage Retrieval\"\n",
"\n",
"\n",
"### Importance of Retrievers\n",
"\n",
"The Retriever has a huge impact on the performance of our overall search pipeline.\n",
"\n",
"\n",
"### Different types of Retrievers\n",
"#### Sparse\n",
"Family of algorithms based on counting the occurences of words (bag-of-words) resulting in very sparse vectors with length = vocab size. \n",
"\n",
"Examples: BM25, TF-IDF \n",
"Pros: Simple, fast, well explainable \n",
"Cons: Relies on exact keyword matches between query and text \n",
" \n",
"\n",
"#### Dense\n",
"These retrievers use neural network models to create \"dense\" embedding vectors. Within this family there are two different approaches: \n",
"\n",
"a) Single encoder: Use a **single model** to embed both query and passage. \n",
"b) Dual-encoder: Use **two models**, one to embed the query and one to embed the passage\n",
"\n",
"Recent work suggests that dual encoders work better, likely because they can deal better with the different nature of query and passage (length, style, syntax ...). \n",
"Pros: Captures semantinc similarity instead of \"word matches\" (e.g. synonyms, related topics ...) \n",
"Cons: Computationally more heavy, initial training of model \n",
"\n",
"\n",
"### \"Dense Passage Retrieval\"\n",
"\n",
"In this Tutorial, we want to highlight one \"Dense Dual-Encoder\" called Dense Passage Retriever. \n",
"It was introdoced by Karpukhin et al. (2020, https://arxiv.org/abs/2004.04906. \n",
"\n",
"Original Abstract: \n",
"\n",
"_\"Open-domain question answering relies on efficient passage retrieval to select candidate contexts, where traditional sparse vector space models, such as TF-IDF or BM25, are the de facto method. In this work, we show that retrieval can be practically implemented using dense representations alone, where embeddings are learned from a small number of questions and passages by a simple dual-encoder framework. When evaluated on a wide range of open-domain QA datasets, our dense retriever outperforms a strong Lucene-BM25 system largely by 9%-19% absolute in terms of top-20 passage retrieval accuracy, and helps our end-to-end QA system establish new state-of-the-art on multiple open-domain QA benchmarks.\"_\n",
"\n",
"Paper: https://arxiv.org/abs/2004.04906 \n",
"Original Code: https://fburl.com/qa-dpr \n",
"\n",
"\n",
"*Use this [link](https://colab.research.google.com/github/deepset-ai/haystack/blob/master/tutorials/Tutorial6_Better_Retrieval_via_DPR.ipynb) to open the notebook in Google Colab.*\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Prepare environment\n",
"\n",
"### Colab: Enable the GPU runtime \n",
"Make sure you enable the GPU runtime to experience decent speed in this tutorial. \n",
"**Runtime -> Change Runtime type -> Hardware accelerator -> GPU**\n",
"You can start Elasticsearch on your local machine instance using Docker. If Docker is not readily available in your environment (e.g. in Colab notebooks), you can also manually download and execute Elasticsearch from source."
"Similarly to the previous tutorials, we download, convert and index some Game of Thrones articles to our DocumentStore"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"07/03/2020 11:46:28 - INFO - haystack.indexing.utils - Found data stored in `data/article_txt_got`. Delete this first if you really want to fetch new data.\n",
"07/03/2020 11:46:28 - INFO - elasticsearch - POST http://localhost:9200/_bulk [status:200 request:0.300s]\n",
"07/03/2020 11:46:28 - INFO - elasticsearch - POST http://localhost:9200/_bulk [status:200 request:0.209s]\n",
"07/03/2020 11:46:28 - INFO - elasticsearch - POST http://localhost:9200/_bulk [status:200 request:0.124s]\n",
"07/03/2020 11:46:29 - INFO - elasticsearch - POST http://localhost:9200/_bulk [status:200 request:0.101s]\n",
"07/03/2020 11:46:29 - INFO - elasticsearch - POST http://localhost:9200/_bulk [status:200 request:0.125s]\n",
"07/03/2020 11:46:29 - INFO - elasticsearch - POST http://localhost:9200/_bulk [status:200 request:0.096s]\n"
]
}
],
"source": [
"# Let's first get some files that we want to use\n",
"# Now, let's write the dicts containing documents to our DB.\n",
"document_store.write_documents(dicts)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Initalize Retriever, Reader, & Finder\n",
"\n",
"### Retriever\n",
"\n",
"**Here:** We use a `DensePassageRetriever`\n",
"\n",
"**Alternatives:**\n",
"\n",
"- The `ElasticsearchRetriever`with custom queries (e.g. boosting) and filters\n",
"- Use `EmbeddingRetriever` to find candidate documents based on the similarity of embeddings (e.g. created via Sentence-BERT)\n",
"- Use `TfidfRetriever` in combination with a SQL or InMemory Document store for simple prototyping and debugging"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"07/03/2020 11:46:29 - INFO - haystack.retriever.dpr_utils - Loading saved model from models/dpr/checkpoint/retriever/single/nq/bert-base-encoder.cp\n",
"# previously indexed documents and update their embedding representation. \n",
"# While this can be a time consuming operation (depending on corpus size), it only needs to be done once. \n",
"# At query time, we only need to embed the query and compare it the existing doc embeddings which is very fast.\n",
"document_store.update_embeddings(retriever)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Reader\n",
"\n",
"Similar to previous Tutorials we now initalize our reader.\n",
"\n",
"Here we use a FARMReader with the *deepset/roberta-base-squad2* model (see: https://huggingface.co/deepset/roberta-base-squad2)\n",
"\n",
"\n",
"\n",
"#### FARMReader"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"pycharm": {
"is_executing": false
}
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"07/03/2020 12:00:52 - INFO - farm.utils - device: cpu n_gpu: 0, distributed training: False, automatic mixed precision training: None\n",
"07/03/2020 12:00:52 - INFO - farm.infer - Could not find `deepset/roberta-base-squad2` locally. Try to download from model hub ...\n",
"07/03/2020 12:00:59 - WARNING - farm.modeling.language_model - Could not automatically detect from language model name what language it is. \n",
"\t We guess it's an *ENGLISH* model ... \n",
"\t If not: Init the language model by supplying the 'language' param.\n",
"07/03/2020 12:01:07 - WARNING - farm.modeling.prediction_head - Some unused parameters are passed to the QuestionAnsweringHead. Might not be a problem. Params: {\"loss_ignore_index\": -1}\n",
"/home/mp/miniconda3/envs/py37/lib/python3.7/site-packages/transformers/tokenization_utils.py:831: FutureWarning: Parameter max_len is deprecated and will be removed in a future release. Use model_max_length instead.\n",
" category=FutureWarning,\n",
"07/03/2020 12:01:11 - INFO - farm.utils - device: cpu n_gpu: 0, distributed training: False, automatic mixed precision training: None\n",
"07/03/2020 12:01:11 - INFO - farm.infer - Got ya 7 parallel workers to do inference ...\n",