{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/share/ninglu_shao/envs/snl/lib/python3.10/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"
]
}
],
"source": [
"from pyserini.search.faiss import FaissSearcher, DprQueryEncoder"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"os.environ[\"JAVA_HOME\"]=\"/share/peitian/Apps/jdk-11.0.2\""
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"/share/peitian/Apps/jdk-11.0.2\n"
]
}
],
"source": [
"!echo $JAVA_HOME"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/share/ninglu_shao/envs/snl/lib/python3.10/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"
]
}
],
"source": [
"from pyserini.search.lucene import LuceneSearcher"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"l_searcher = LuceneSearcher(\"/share/ninglu_shao/code/Citation/lucene-index.wikipedia-dpr-100w.20210120.d1b9e6\")\n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"ename": "AttributeError",
"evalue": "'NoneType' object has no attribute 'raw'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m/share/ninglu_shao/code/Citation/test_pyserini.ipynb 单元格 6\u001b[0m line \u001b[0;36m2\n\u001b[1;32m 1\u001b[0m doc \u001b[39m=\u001b[39m l_searcher\u001b[39m.\u001b[39mdoc(\u001b[39m\"\u001b[39m\u001b[39m0\u001b[39m\u001b[39m\"\u001b[39m)\n\u001b[0;32m----> 2\u001b[0m \u001b[39mprint\u001b[39m(doc\u001b[39m.\u001b[39;49mraw())\n",
"\u001b[0;31mAttributeError\u001b[0m: 'NoneType' object has no attribute 'raw'"
]
}
],
"source": [
"doc = l_searcher.doc(\"0\")"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{\n",
" \"id\" : \"1\",\n",
" \"contents\" : \"Aaron\\nAaron Aaron ( or ; \\\"\\\"Ahärôn\\\"\\\") is a prophet, high priest, and the brother of Moses in the Abrahamic religions. Knowledge of Aaron, along with his brother Moses, comes exclusively from religious texts, such as the Bible and Quran. The Hebrew Bible relates that, unlike Moses, who grew up in the Egyptian royal court, Aaron and his elder sister Miriam remained with their kinsmen in the eastern border-land of Egypt (Goshen). When Moses first confronted the Egyptian king about the Israelites, Aaron served as his brother's spokesman (\\\"\\\"prophet\\\"\\\") to the Pharaoh. Part of the Law (Torah) that Moses received from\"\n",
"}\n"
]
}
],
"source": [
"doc = l_searcher.doc(\"1\")\n",
"print(doc.raw())"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"21015324"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"l_searcher.num_docs"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"encoder = DprQueryEncoder('/share/LMs/models--facebook--dpr-question_encoder-single-nq-base/snapshots/d04a52f6d2f96c60117a925e8c24c4043a75f265')"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"searcher = FaissSearcher(\"/share/ninglu_shao/code/Citation/faiss.wikipedia-dpr-100w.dpr_single-nq.20200115.cd5034\", encoder)"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"docid_path = \"/share/ninglu_shao/code/Citation/faiss.wikipedia-dpr-100w.dpr_single-nq.20200115.cd5034/docid\"\n",
"\n",
"id_f = open(docid_path, 'r')\n",
"docids = [line.rstrip() for line in id_f.readlines()]\n",
"id_f.close()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"21015320"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(docids)"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import faiss\n",
"\n",
"index = faiss.read_index(\"/share/ninglu_shao/code/Citation/faiss.wikipedia-dpr-100w.dpr_single-nq.20200115.cd5034/index\")"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['__class__',\n",
" '__delattr__',\n",
" '__dict__',\n",
" '__dir__',\n",
" '__doc__',\n",
" '__eq__',\n",
" '__format__',\n",
" '__ge__',\n",
" '__getattribute__',\n",
" '__getstate__',\n",
" '__gt__',\n",
" '__hash__',\n",
" '__init__',\n",
" '__init_subclass__',\n",
" '__le__',\n",
" '__lt__',\n",
" '__module__',\n",
" '__ne__',\n",
" '__new__',\n",
" '__reduce__',\n",
" '__reduce_ex__',\n",
" '__repr__',\n",
" '__setattr__',\n",
" '__setstate__',\n",
" '__sizeof__',\n",
" '__str__',\n",
" '__subclasshook__',\n",
" '__swig_destroy__',\n",
" '__weakref__',\n",
" 'add',\n",
" 'add_c',\n",
" 'add_with_ids',\n",
" 'add_with_ids_c',\n",
" 'assign',\n",
" 'assign_c',\n",
" 'check_compatible_for_merge',\n",
" 'code_size',\n",
" 'codes',\n",
" 'compute_distance_subset',\n",
" 'compute_residual',\n",
" 'compute_residual_n',\n",
" 'd',\n",
" 'get_CodePacker',\n",
" 'get_FlatCodesDistanceComputer',\n",
" 'get_distance_computer',\n",
" 'get_xb',\n",
" 'is_trained',\n",
" 'merge_from',\n",
" 'metric_arg',\n",
" 'metric_type',\n",
" 'ntotal',\n",
" 'range_search',\n",
" 'range_search_c',\n",
" 'reconstruct',\n",
" 'reconstruct_batch',\n",
" 'reconstruct_batch_c',\n",
" 'reconstruct_c',\n",
" 'reconstruct_n',\n",
" 'reconstruct_n_c',\n",
" 'remove_ids',\n",
" 'remove_ids_c',\n",
" 'reset',\n",
" 'sa_code_size',\n",
" 'sa_decode',\n",
" 'sa_decode_c',\n",
" 'sa_encode',\n",
" 'sa_encode_c',\n",
" 'search',\n",
" 'search_and_reconstruct',\n",
" 'search_and_reconstruct_c',\n",
" 'search_c',\n",
" 'this',\n",
" 'thisown',\n",
" 'train',\n",
" 'train_c',\n",
" 'verbose']"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dir(index)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n",
"21015320\n"
]
}
],
"source": [
"print(index.is_trained)\n",
"print(index.ntotal)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"hits = searcher.search('What is the capital of England?')"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" 1 236683 76.48925\n",
" 2 236560 76.48925\n",
" 3 3501858 75.72459\n",
" 4 119415 75.28250\n",
" 5 236591 75.18885\n",
" 6 429108 75.02307\n",
" 7 236597 74.69403\n",
" 8 4837544 74.68403\n",
" 9 119422 74.60806\n",
"10 10971602 74.33704\n"
]
}
],
"source": [
"for i in range(0, 10):\n",
" print(f'{i+1:2} {hits[i].docid:7} {hits[i].score:.5f}')"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"ename": "AttributeError",
"evalue": "'FaissSearcher' object has no attribute 'ssearcher'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m/share/ninglu_shao/code/Citation/test_pyserini.ipynb 单元格 6\u001b[0m line \u001b[0;36m1\n\u001b[0;32m----> 1\u001b[0m doc \u001b[39m=\u001b[39m searcher\u001b[39m.\u001b[39;49mdoc(\u001b[39m\"\u001b[39;49m\u001b[39m3752133 \u001b[39;49m\u001b[39m\"\u001b[39;49m)\n",
"File \u001b[0;32m/share/ninglu_shao/envs/snl/lib/python3.10/site-packages/pyserini/search/faiss/_searcher.py:590\u001b[0m, in \u001b[0;36mFaissSearcher.doc\u001b[0;34m(self, docid)\u001b[0m\n\u001b[1;32m 574\u001b[0m \u001b[39mdef\u001b[39;00m \u001b[39mdoc\u001b[39m(\u001b[39mself\u001b[39m, docid: Union[\u001b[39mstr\u001b[39m, \u001b[39mint\u001b[39m]) \u001b[39m-\u001b[39m\u001b[39m>\u001b[39m Optional[Document]:\n\u001b[1;32m 575\u001b[0m \u001b[39m \u001b[39m\u001b[39m\"\"\"Return the :class:`Document` corresponding to ``docid``. Since dense indexes don't store documents\u001b[39;00m\n\u001b[1;32m 576\u001b[0m \u001b[39m but sparse indexes do, route over to corresponding sparse index (according to prebuilt_index_info.py)\u001b[39;00m\n\u001b[1;32m 577\u001b[0m \u001b[39m and use its doc API \u001b[39;00m\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 588\u001b[0m \u001b[39m :class:`Document` corresponding to the ``docid``.\u001b[39;00m\n\u001b[1;32m 589\u001b[0m \u001b[39m \"\"\"\u001b[39;00m\n\u001b[0;32m--> 590\u001b[0m \u001b[39mreturn\u001b[39;00m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39mssearcher\u001b[39m.\u001b[39mdoc(docid) \u001b[39mif\u001b[39;00m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mssearcher \u001b[39melse\u001b[39;00m \u001b[39mNone\u001b[39;00m\n",
"\u001b[0;31mAttributeError\u001b[0m: 'FaissSearcher' object has no attribute 'ssearcher'"
]
}
],
"source": [
"doc = searcher.doc(\"3752133 \")"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"d = 64 # dimension\n",
"nb = 100000 # database size\n",
"nq = 10000 # nb of queries\n",
"np.random.seed(1234) # make reproducible\n",
"xb = np.random.random((nb, d)).astype('float32')\n",
"xb[:, 0] += np.arange(nb) / 1000.\n",
"xq = np.random.random((nq, d)).astype('float32')\n",
"xq[:, 0] += np.arange(nq) / 1000."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n",
"100000\n"
]
}
],
"source": [
"import faiss # make faiss available\n",
"\n",
"index = faiss.IndexFlatL2(d) # build the index\n",
"print(index.is_trained)\n",
"index.add(xb) # add vectors to the index\n",
"print(index.ntotal)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[ 0 393 363 78]\n",
" [ 1 555 277 364]\n",
" [ 2 304 101 13]\n",
" [ 3 173 18 182]\n",
" [ 4 288 370 531]]\n",
"[[0. 7.1751738 7.20763 7.2511625]\n",
" [0. 6.3235645 6.684581 6.799946 ]\n",
" [0. 5.7964087 6.391736 7.2815123]\n",
" [0. 7.2779055 7.5279875 7.662846 ]\n",
" [0. 6.7638035 7.2951202 7.3688145]]\n",
"[[ 381 207 210 477]\n",
" [ 526 911 142 72]\n",
" [ 838 527 1290 425]\n",
" [ 196 184 164 359]\n",
" [ 526 377 120 425]]\n",
"[[ 9900 10500 9309 9831]\n",
" [11055 10895 10812 11321]\n",
" [11353 11103 10164 9787]\n",
" [10571 10664 10632 9638]\n",
" [ 9628 9554 10036 9582]]\n"
]
}
],
"source": [
"k = 4 # we want to see 4 nearest neighbors\n",
"D, I = index.search(xb[:5], k) # sanity check\n",
"print(I)\n",
"print(D)\n",
"D, I = index.search(xq, k) # actual search\n",
"print(I[:5]) # neighbors of the 5 first queries\n",
"print(I[-5:]) # neighbors of the 5 last queries"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"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.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 2
}