{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# SPTAG python wrapper tutorial \n", "\n", "To end-to-end build a vector search online service, it contains two steps:\n", "- Offline build SPTAG index for database vectors\n", "- Online serve the index to support vector search requests from the clients\n", "\n", "## Offline build SPTAG index\n", "\n", "> Prepare input vectors and metadatas for SPTAG" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import os\n", "import shutil\n", "import numpy as np\n", "\n", "vector_number = 1000\n", "vector_dimension = 100\n", "\n", "# Randomly generate the database vectors. Currently SPTAG only support int8, int16 and float32 data type.\n", "x = np.random.rand(vector_number, vector_dimension).astype(np.float32) \n", "\n", "# Prepare metadata for each vectors, separate them by '\\n'. Currently SPTAG python wrapper only support '\\n' as the separator\n", "m = ''\n", "for i in range(vector_number):\n", " m += str(i) + '\\n'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> Build SPTAG index for database vectors **x**" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['deletes.bin',\n", " 'graph.bin',\n", " 'indexloader.ini',\n", " 'metadata.bin',\n", " 'metadataIndex.bin',\n", " 'tree.bin',\n", " 'vectors.bin']" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import SPTAG\n", "\n", "index = SPTAG.AnnIndex('BKT', 'Float', vector_dimension)\n", "\n", "# Set the thread number to speed up the build procedure in parallel \n", "index.SetBuildParam(\"NumberOfThreads\", '4', \"Index\")\n", "\n", "# Set the distance type. Currently SPTAG only support Cosine and L2 distances. Here Cosine distance is not the Cosine similarity. The smaller Cosine distance it is, the better.\n", "index.SetBuildParam(\"DistCalcMethod\", 'L2', \"Index\") \n", "\n", "if (os.path.exists(\"sptag_index\")):\n", " shutil.rmtree(\"sptag_index\")\n", "if index.BuildWithMetaData(x, m, vector_number, False, False):\n", " index.Save(\"sptag_index\") # Save the index to the disk\n", "\n", "os.listdir('sptag_index')" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[450, 247, 150, 832, 626, 828, 253, 471, 243, 365]\n", "[11.603649139404297, 12.164414405822754, 12.225785255432129, 12.336504936218262, 12.416375160217285, 12.481977462768555, 12.573633193969727, 12.616722106933594, 12.708147048950195, 12.821012496948242]\n", "[b'450\\n', b'247\\n', b'150\\n', b'832\\n', b'626\\n', b'828\\n', b'253\\n', b'471\\n', b'243\\n', b'365\\n']\n", "[(450, 11.603649139404297, b'450\\n'), (247, 12.164414405822754, b'247\\n'), (150, 12.225785255432129, b'150\\n'), (832, 12.336504936218262, b'832\\n'), (626, 12.416375160217285, b'626\\n'), (828, 12.481977462768555, b'828\\n'), (253, 12.573633193969727, b'253\\n'), (471, 12.616722106933594, b'471\\n'), (243, 12.708147048950195, b'243\\n'), (365, 12.821012496948242, b'365\\n')]\n" ] } ], "source": [ "# Local index test on the vector search\n", "index = SPTAG.AnnIndex.Load('sptag_index')\n", "\n", "# prepare query vector\n", "q = np.random.rand(vector_dimension).astype(np.float32)\n", "\n", "result = index.SearchWithMetaData(q, 10) # Search k=3 nearest vectors for query vector q\n", "print (result[0]) # nearest k vector ids\n", "print (result[1]) # nearest k vector distances\n", "print (result[2]) # nearest k vector metadatas\n", "\n", "results = []\n", "iterator = index.GetIterator(q)\n", "while True:\n", " result = iterator.Next(10)\n", " #print (result[0]) # vector ids of the batch index scan candidates\n", " #print (result[1]) # vector distances of the batch index scan candidates\n", " #print (result[2]) # vector metadatas of the batch index scan candidates\n", " #print (result[3]) # relaxed monotonicity of the batch index scan candidates\n", " for j in range(len(result[0])):\n", " results.append((result[0][j], result[1][j], result[2][j]))\n", " if len(result[0]) < 10 or result[3][0] == True: break\n", "iterator.Close()\n", "\n", "results.sort(key = lambda item: item[1])\n", "print (results[0:10])\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> Build SPTAG index for database vector **x** with PQ quantization" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "CompletedProcess(args='Quantizer.exe -d 100 -v Float -f DEFAULT -i sptag_index\\\\vectors.bin -o quan_doc_vectors.bin -oq quantizer.bin -qt PQQuantizer -qd 50 -ts 1000 -norm false', returncode=0)\n", "(1000, 50)\n" ] } ], "source": [ "import subprocess\n", "import struct\n", "import numpy as np\n", "\n", "if (os.path.exists(\"quantizer.bin\")):\n", " os.remove(\"quantizer.bin\")\n", "if (os.path.exists(\"quan_doc_vectors.bin\")):\n", " os.remove(\"quan_doc_vectors.bin\")\n", "cmd = \"Quantizer.exe -d %d -v Float -f DEFAULT -i sptag_index\\\\vectors.bin -o quan_doc_vectors.bin -oq quantizer.bin -qt PQQuantizer -qd %d -ts %d -norm false\" % (vector_dimension, int(vector_dimension / 2), vector_number)\n", "result = subprocess.run(cmd)\n", "print (result) \n", "# For SPTAG index with quantization:\n", "# Cosine distance: norm -> true and use L2 for index build\n", "# L2 distance: norm -> false and use L2 for index build\n", "\n", "f = open('quan_doc_vectors.bin', 'rb')\n", "r = struct.unpack('i', f.read(4))[0]\n", "c = struct.unpack('i', f.read(4))[0]\n", "quan_x = np.frombuffer(f.read(r*c), dtype=np.uint8).reshape((r,c))\n", "f.close()\n", "print (quan_x.shape)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['deletes.bin',\n", " 'graph.bin',\n", " 'indexloader.ini',\n", " 'metadata.bin',\n", " 'metadataIndex.bin',\n", " 'quantizer.bin',\n", " 'tree.bin',\n", " 'vectors.bin']" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import SPTAG\n", "\n", "index = SPTAG.AnnIndex('BKT', 'UInt8', int(vector_dimension / 2))\n", "\n", "# Set the thread number to speed up the build procedure in parallel \n", "index.SetBuildParam(\"NumberOfThreads\", '4', \"Index\")\n", "\n", "# Set the distance type. Currently SPTAG only support Cosine and L2 distances. Here Cosine distance is not the Cosine similarity. The smaller Cosine distance it is, the better.\n", "index.SetBuildParam(\"DistCalcMethod\", 'L2', \"Index\") \n", "\n", "if (os.path.exists(\"quan_sptag_index\")):\n", " shutil.rmtree(\"quan_sptag_index\")\n", "if index.LoadQuantizer(\"quantizer.bin\") and index.BuildWithMetaData(quan_x, m, vector_number, False, False):\n", " index.Save(\"quan_sptag_index\") # Save the index to the disk\n", "\n", "os.listdir('quan_sptag_index')" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[450, 247, 832, 626, 150, 253, 471, 828, 243, 207, 365, 823]\n", "[11.497368812561035, 12.21573257446289, 12.328060150146484, 12.369790077209473, 12.420766830444336, 12.47612476348877, 12.48221206665039, 12.526467323303223, 12.802266120910645, 12.819355010986328, 12.876933097839355, 12.913871765136719]\n", "[b'450\\n', b'247\\n', b'832\\n', b'626\\n', b'150\\n', b'253\\n', b'471\\n', b'828\\n', b'243\\n', b'207\\n', b'365\\n', b'823\\n']\n" ] } ], "source": [ "# Local index test on the vector search\n", "index = SPTAG.AnnIndex.Load('quan_sptag_index')\n", "index.SetQuantizerADC(True)\n", "result = index.SearchWithMetaData(q, 12) # Search k=3 nearest vectors for query vector q\n", "print (result[0]) # nearest k vector ids\n", "print (result[1]) # nearest k vector distances\n", "print (result[2]) # nearest k vector metadatas" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['HeadIndex',\n", " 'indexloader.ini',\n", " 'metadata.bin',\n", " 'metadataIndex.bin',\n", " 'SPTAGFullList.bin',\n", " 'SPTAGHeadVectorIDs.bin',\n", " 'SPTAGHeadVectors.bin']" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import SPTAG\n", "\n", "index = SPTAG.AnnIndex('SPANN', 'Float', vector_dimension)\n", "\n", "# Set the thread number to speed up the build procedure in parallel \n", "index.SetBuildParam(\"IndexAlgoType\", \"BKT\", \"Base\")\n", "index.SetBuildParam(\"IndexDirectory\", \"spann_index\", \"Base\")\n", "index.SetBuildParam(\"DistCalcMethod\", \"L2\", \"Base\")\n", "\n", "index.SetBuildParam(\"isExecute\", \"true\", \"SelectHead\")\n", "index.SetBuildParam(\"NumberOfThreads\", \"4\", \"SelectHead\")\n", "index.SetBuildParam(\"Ratio\", \"0.2\", \"SelectHead\") # index.SetBuildParam(\"Count\", \"200\", \"SelectHead\")\n", "\n", "index.SetBuildParam(\"isExecute\", \"true\", \"BuildHead\")\n", "index.SetBuildParam(\"RefineIterations\", \"3\", \"BuildHead\")\n", "index.SetBuildParam(\"NumberOfThreads\", \"4\", \"BuildHead\")\n", "\n", "index.SetBuildParam(\"isExecute\", \"true\", \"BuildSSDIndex\")\n", "index.SetBuildParam(\"BuildSsdIndex\", \"true\", \"BuildSSDIndex\")\n", "index.SetBuildParam(\"PostingPageLimit\", \"12\", \"BuildSSDIndex\")\n", "index.SetBuildParam(\"SearchPostingPageLimit\", \"12\", \"BuildSSDIndex\")\n", "index.SetBuildParam(\"NumberOfThreads\", \"4\", \"BuildSSDIndex\")\n", "index.SetBuildParam(\"InternalResultNum\", \"32\", \"BuildSSDIndex\")\n", "index.SetBuildParam(\"SearchInternalResultNum\", \"64\", \"BuildSSDIndex\")\n", "\n", "if (os.path.exists(\"spann_index\")):\n", " shutil.rmtree(\"spann_index\")\n", "\n", "if index.BuildWithMetaData(x, m, vector_number, False, False):\n", " index.Save(\"spann_index\") # Save the index to the disk\n", "\n", "os.listdir('spann_index')" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[450, 247, 150, 832, 626, 828, 253, 471, 243, 365, 207, 823]\n", "[11.603649139404297, 12.164414405822754, 12.225785255432129, 12.336504936218262, 12.416375160217285, 12.481977462768555, 12.573633193969727, 12.616722106933594, 12.708147048950195, 12.821012496948242, 12.878414154052734, 13.01927375793457]\n", "[b'450\\n', b'247\\n', b'150\\n', b'832\\n', b'626\\n', b'828\\n', b'253\\n', b'471\\n', b'243\\n', b'365\\n', b'207\\n', b'823\\n']\n" ] } ], "source": [ "index = SPTAG.AnnIndex.Load('spann_index')\n", "result = index.SearchWithMetaData(q, 12) # Search k=3 nearest vectors for query vector q\n", "print (result[0]) # nearest k vector ids\n", "print (result[1]) # nearest k vector distances\n", "print (result[2]) # nearest k vector metadatas" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['HeadIndex',\n", " 'indexloader.ini',\n", " 'metadata.bin',\n", " 'metadataIndex.bin',\n", " 'quantizer.bin',\n", " 'SPTAGFullList.bin',\n", " 'SPTAGHeadVectorIDs.bin',\n", " 'SPTAGHeadVectors.bin']" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import SPTAG\n", "\n", "index = SPTAG.AnnIndex('SPANN', 'UInt8', int(vector_dimension / 2))\n", "\n", "# Set the thread number to speed up the build procedure in parallel \n", "index.SetBuildParam(\"IndexAlgoType\", \"BKT\", \"Base\")\n", "index.SetBuildParam(\"IndexDirectory\", \"spann_quan_index\", \"Base\")\n", "index.SetBuildParam(\"DistCalcMethod\", \"L2\", \"Base\")\n", "index.SetBuildParam(\"QuantizerFilePath\", \"quantizer.bin\", \"Base\")\n", "\n", "index.SetBuildParam(\"isExecute\", \"true\", \"SelectHead\")\n", "index.SetBuildParam(\"NumberOfThreads\", \"4\", \"SelectHead\")\n", "index.SetBuildParam(\"Ratio\", \"0.2\", \"SelectHead\") # index.SetBuildParam(\"Count\", \"200\", \"SelectHead\")\n", "\n", "index.SetBuildParam(\"isExecute\", \"true\", \"BuildHead\")\n", "index.SetBuildParam(\"RefineIterations\", \"3\", \"BuildHead\")\n", "index.SetBuildParam(\"NumberOfThreads\", \"4\", \"BuildHead\")\n", "\n", "index.SetBuildParam(\"isExecute\", \"true\", \"BuildSSDIndex\")\n", "index.SetBuildParam(\"BuildSsdIndex\", \"true\", \"BuildSSDIndex\")\n", "index.SetBuildParam(\"PostingPageLimit\", \"12\", \"BuildSSDIndex\")\n", "index.SetBuildParam(\"SearchPostingPageLimit\", \"12\", \"BuildSSDIndex\")\n", "index.SetBuildParam(\"NumberOfThreads\", \"4\", \"BuildSSDIndex\")\n", "index.SetBuildParam(\"InternalResultNum\", \"32\", \"BuildSSDIndex\")\n", "index.SetBuildParam(\"SearchInternalResultNum\", \"64\", \"BuildSSDIndex\")\n", "\n", "if (os.path.exists(\"spann_quan_index\")):\n", " shutil.rmtree(\"spann_quan_index\")\n", "\n", "if index.LoadQuantizer(\"quantizer.bin\") and index.BuildWithMetaData(quan_x, m, vector_number, False, False):\n", " index.Save(\"spann_quan_index\") # Save the index to the disk\n", "\n", "os.listdir('spann_quan_index')" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[450, 247, 832, 626, 150, 253, 471, 828, 243, 207, 365, 823]\n", "[11.497368812561035, 12.21573257446289, 12.328060150146484, 12.369790077209473, 12.420766830444336, 12.47612476348877, 12.48221206665039, 12.526467323303223, 12.802266120910645, 12.819355010986328, 12.876933097839355, 12.913871765136719]\n", "[b'450\\n', b'247\\n', b'832\\n', b'626\\n', b'150\\n', b'253\\n', b'471\\n', b'828\\n', b'243\\n', b'207\\n', b'365\\n', b'823\\n']\n" ] } ], "source": [ "index = SPTAG.AnnIndex.Load('spann_quan_index')\n", "index.SetQuantizerADC(True)\n", "result = index.SearchWithMetaData(q, 12) # Search k=3 nearest vectors for query vector q\n", "print (result[0]) # nearest k vector ids\n", "print (result[1]) # nearest k vector distances\n", "print (result[2]) # nearest k vector metadatas" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Online serve the index\n", "\n", "Start the vector search service on the host machine which listens for the client requests on the port 8000\n", "\n", "> Write a server configuration file **service.ini** as follows:\n", "\n", "```bash\n", "[Service]\n", "ListenAddr=0.0.0.0\n", "ListenPort=8000\n", "ThreadNumber=8\n", "SocketThreadNumber=8\n", "\n", "[QueryConfig]\n", "DefaultMaxResultNumber=6\n", "DefaultSeparator=|\n", "\n", "[Index]\n", "List=MyIndex\n", "\n", "[Index_MyIndex]\n", "IndexFolder=sptag_index\n", "```\n", "\n", "> Start the server on the host machine\n", "\n", "```bash\n", "Server.exe -m socket -c service.ini\n", "```\n", "\n", "It will print the follow messages:\n", "\n", "```bash\n", "Setting TreeFilePath with value tree.bin\n", "Setting GraphFilePath with value graph.bin\n", "Setting VectorFilePath with value vectors.bin\n", "Setting DeleteVectorFilePath with value deletes.bin\n", "Setting BKTNumber with value 1\n", "Setting BKTKmeansK with value 32\n", "Setting BKTLeafSize with value 8\n", "Setting Samples with value 1000\n", "Setting TPTNumber with value 32\n", "Setting TPTLeafSize with value 2000\n", "Setting NumTopDimensionTpTreeSplit with value 5\n", "Setting NeighborhoodSize with value 32\n", "Setting GraphNeighborhoodScale with value 2\n", "Setting GraphCEFScale with value 2\n", "Setting RefineIterations with value 2\n", "Setting CEF with value 1000\n", "Setting MaxCheckForRefineGraph with value 8192\n", "Setting NumberOfThreads with value 4\n", "Setting DistCalcMethod with value Cosine\n", "Setting DeletePercentageForRefine with value 0.400000\n", "Setting AddCountForRebuild with value 1000\n", "Setting MaxCheck with value 8192\n", "Setting ThresholdOfNumberOfContinuousNoBetterPropagation with value 3\n", "Setting NumberOfInitialDynamicPivots with value 50\n", "Setting NumberOfOtherDynamicPivots with value 4\n", "Load Vector From sptag_index\\vectors.bin\n", "Load Vector (100, 10) Finish!\n", "Load BKT From sptag_index\\tree.bin\n", "Load BKT (1,101) Finish!\n", "Load Graph From sptag_index\\graph.bin\n", "Load Graph (100, 32) Finish!\n", "Load DeleteID From sptag_index\\deletes.bin\n", "Load DeleteID (100, 1) Finish!\n", "Start to listen 0.0.0.0:8000 ...\n", "```\n", "\n", "> Start python client to connect to the server and send vector search request." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import SPTAGClient\n", "import time\n", "\n", "# connect to the server\n", "client = SPTAGClient.AnnClient('127.0.0.1', '8000')\n", "while not client.IsConnected():\n", " time.sleep(1)\n", "client.SetTimeoutMilliseconds(18000)\n", "\n", "k = 3\n", "vector_dimension = 10\n", "# prepare query vector\n", "q = np.random.rand(vector_dimension).astype(np.float32)\n", "\n", "result = client.Search(q, k, 'Float', True) # AnnClient.Search(query_vector, knn, data_type, with_metadata)\n", "\n", "print (result[0]) # nearest k vector ids\n", "print (result[1]) # nearest k vector distances\n", "print (result[2]) # nearest k vector metadatas\n", "\n" ] } ], "metadata": { "file_extension": ".py", "kernelspec": { "display_name": "Python 3.9.12 64-bit", "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.9.3" }, "mimetype": "text/x-python", "name": "python", "npconvert_exporter": "python", "pygments_lexer": "ipython2", "version": 2, "vscode": { "interpreter": { "hash": "81794d4967e6c3204c66dcd87b604927b115b27c00565d3d43f05ba2f3a2cb0d" } } }, "nbformat": 4, "nbformat_minor": 2 }