From 197820457cbc469d8976d7b2c791a3697ec0dba3 Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Wed, 28 Dec 2022 22:05:06 +0200 Subject: [PATCH 1/3] implement batching --- pinecone/index.py | 50 ++++++++++++++++++++++++++++++++++++----------- requirements.txt | 3 ++- 2 files changed, 41 insertions(+), 12 deletions(-) diff --git a/pinecone/index.py b/pinecone/index.py index 9a263a222..5a57a6ef5 100644 --- a/pinecone/index.py +++ b/pinecone/index.py @@ -1,7 +1,7 @@ # # Copyright (c) 2020-2021 Pinecone Systems Inc. All right reserved. # - +from tqdm import tqdm from collections.abc import Iterable from typing import Union, List, Tuple, Optional, Dict, Any @@ -64,6 +64,8 @@ def __init__(self, index_name: str, pool_threads=1): def upsert(self, vectors: Union[List[Vector], List[Tuple]], namespace: Optional[str] = None, + batch_size: Optional[int] = None, + show_progress: bool = True, **kwargs) -> UpsertResponse: """ The upsert operation writes vectors into a namespace. @@ -93,26 +95,43 @@ def upsert(self, Note: the dimension of each vector must match the dimension of the index. namespace (str): The namespace to write to. If not specified, the default namespace is used. [optional] - + batch_size (int): The number of vectors to upsert in each batch. + If not specified, all vectors will be upserted in a single batch. [optional] + show_progress (bool): Whether to show a progress bar using tqdm. + Applied only if batch_size is provided. Defaults to True. Keyword Args: Supports OpenAPI client keyword arguments. See pinecone.core.client.models.UpsertRequest for more details. Returns: UpsertResponse, includes the number of vectors upserted. """ _check_type = kwargs.pop('_check_type', False) - args_dict = self._parse_args_to_dict([('namespace', namespace)]) - def _vector_transform(item): - if isinstance(item, Vector): - return item - if isinstance(item, tuple): - id, values, metadata = fix_tuple_length(item, 3) - return Vector(id=id, values=values, metadata=metadata or {}, _check_type=_check_type) - raise ValueError(f"Invalid vector value passed: cannot interpret type {type(item)}") + if batch_size is None: + return self._upsert_batch(vectors, namespace, **kwargs) + + if not isinstance(batch_size, int) or batch_size <= 0: + raise ValueError('batch_size must be a positive integer') + + pbar = tqdm(total=len(vectors), disable=not show_progress, desc='Upserted vectors') + total_upserted = 0 + for i in range(0, len(vectors), batch_size): + batch = vectors[i:i + batch_size] + batch_result = self._upsert_batch(batch, namespace, **kwargs) + total_upserted += batch_result.upserted_count + pbar.update(len(batch)) + return UpsertResponse(upserted_count=total_upserted) + + def _upsert_batch(self, + vectors: List[Vector], + namespace: Optional[str], + _check_type: bool, + **kwargs) -> UpsertResponse: + vectors = list(map(self._transform_upsert_vector, vectors)) + args_dict = self._parse_args_to_dict([('namespace', namespace)]) return self._vector_api.upsert( UpsertRequest( - vectors=list(map(_vector_transform, vectors)), + vectors=vectors, **args_dict, _check_type=_check_type, **{k: v for k, v in kwargs.items() if k not in _OPENAPI_ENDPOINT_PARAMS} @@ -120,6 +139,15 @@ def _vector_transform(item): **{k: v for k, v in kwargs.items() if k in _OPENAPI_ENDPOINT_PARAMS} ) + @staticmethod + def _transform_upsert_vector(item: Union[Vector, Tuple], _check_type): + if isinstance(item, Vector): + return item + if isinstance(item, tuple): + id, values, metadata = fix_tuple_length(item, 3) + return Vector(id=id, values=values, metadata=metadata or {}, _check_type=_check_type) + raise ValueError(f"Invalid vector value passed: cannot interpret type {type(item)}") + @validate_and_convert_errors def delete(self, ids: Optional[List[str]] = None, diff --git a/requirements.txt b/requirements.txt index 05b55a2ad..823317270 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,4 +5,5 @@ typing-extensions>=3.7.4 dnspython>=2.0.0 # openapi generated client: python_dateutil >= 2.5.3 -urllib3 >= 1.21.1 \ No newline at end of file +urllib3 >= 1.21.1 +tqdm >= 4.64.1 \ No newline at end of file From 534812d9645172e274d9b5f6257e343789699e13 Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Thu, 29 Dec 2022 16:41:10 +0200 Subject: [PATCH 2/3] add tests and impel for grpc index --- pinecone/core/grpc/index_grpc.py | 47 +++++++++-- pinecone/index.py | 18 +++-- tests/unit/test_grpc_index.py | 126 ++++++++++++++++++++++++++++- tests/unit/test_index.py | 135 ++++++++++++++++++++++++++++++- 4 files changed, 313 insertions(+), 13 deletions(-) diff --git a/pinecone/core/grpc/index_grpc.py b/pinecone/core/grpc/index_grpc.py index 6fe2c971f..fa1b6de12 100644 --- a/pinecone/core/grpc/index_grpc.py +++ b/pinecone/core/grpc/index_grpc.py @@ -10,6 +10,8 @@ import grpc from google.protobuf import json_format from grpc._channel import _InactiveRpcError, _MultiThreadedRendezvous +from tqdm import tqdm + from pinecone import FetchResponse, QueryResponse, ScoredVector, SingleQueryResults, DescribeIndexStatsResponse from pinecone.config import Config from pinecone.core.client.model.namespace_summary import NamespaceSummary @@ -255,6 +257,8 @@ def upsert(self, vectors: Union[List[GRPCVector], List[Tuple]], async_req: bool = False, namespace: Optional[str] = None, + batch_size: Optional[int] = None, + show_progress: bool = True, **kwargs) -> Union[UpsertResponse, PineconeGrpcFuture]: """ The upsert operation writes vectors into a namespace. @@ -281,13 +285,21 @@ def upsert(self, Note: the dimension of each vector must match the dimension of the index. async_req (bool): If True, the upsert operation will be performed asynchronously. + Cannot be used with batch_size. Defaults to False. See: https://docs.pinecone.io/docs/performance-tuning [optional] namespace (str): The namespace to write to. If not specified, the default namespace is used. [optional] + batch_size (int): The number of vectors to upsert in each batch. + Cannot be used with async_req=Ture. + If not specified, all vectors will be upserted in a single batch. [optional] + show_progress (bool): Whether to show a progress bar using tqdm. + Applied only if batch_size is provided. Default is True. Returns: UpsertResponse, contains the number of vectors upserted """ - - args_dict = self._parse_non_empty_args([('namespace', namespace)]) + if async_req and batch_size is not None: + raise ValueError('async_req is not supported when batch_size is provided.' + 'To upsert in parallel, please follow: ' + 'https://docs.pinecone.io/docs/performance-tuning') def _vector_transform(item): if isinstance(item, GRPCVector): @@ -299,12 +311,37 @@ def _vector_transform(item): timeout = kwargs.pop('timeout', None) - request = UpsertRequest(vectors=list(map(_vector_transform, vectors)), **args_dict, **kwargs) + vectors = list(map(_vector_transform, vectors)) if async_req: + args_dict = self._parse_non_empty_args([('namespace', namespace)]) + request = UpsertRequest(vectors=vectors, **args_dict, **kwargs) future = self._wrap_grpc_call(self.stub.Upsert.future, request, timeout=timeout) return PineconeGrpcFuture(future) - else: - return self._wrap_grpc_call(self.stub.Upsert, request, timeout=timeout) + + if batch_size is None: + return self._upsert_batch(vectors, namespace, timeout=timeout, **kwargs) + + if not isinstance(batch_size, int) or batch_size <= 0: + raise ValueError('batch_size must be a positive integer') + + pbar = tqdm(total=len(vectors), disable=not show_progress, desc='Upserted vectors') + total_upserted = 0 + for i in range(0, len(vectors), batch_size): + batch_result = self._upsert_batch(vectors[i:i + batch_size], namespace, timeout=timeout, **kwargs) + pbar.update(batch_result.upserted_count) + # we can't use here pbar.n for the case show_progress=False + total_upserted += batch_result.upserted_count + + return UpsertResponse(upserted_count=total_upserted) + + def _upsert_batch(self, + vectors: List[GRPCVector], + namespace: Optional[str], + timeout: Optional[float], + **kwargs) -> UpsertResponse: + args_dict = self._parse_non_empty_args([('namespace', namespace)]) + request = UpsertRequest(vectors=vectors, **args_dict) + return self._wrap_grpc_call(self.stub.Upsert, request, timeout=timeout, **kwargs) def delete(self, ids: Optional[List[str]] = None, diff --git a/pinecone/index.py b/pinecone/index.py index aa6b02bff..2f8260ec0 100644 --- a/pinecone/index.py +++ b/pinecone/index.py @@ -100,7 +100,7 @@ def upsert(self, batch_size (int): The number of vectors to upsert in each batch. If not specified, all vectors will be upserted in a single batch. [optional] show_progress (bool): Whether to show a progress bar using tqdm. - Applied only if batch_size is provided. Defaults to True. + Applied only if batch_size is provided. Default is True. Keyword Args: Supports OpenAPI client keyword arguments. See pinecone.core.client.models.UpsertRequest for more details. @@ -108,6 +108,11 @@ def upsert(self, """ _check_type = kwargs.pop('_check_type', False) + if kwargs.get('async_req', False) and batch_size is not None: + raise ValueError('async_req is not supported when batch_size is provided.' + 'To upsert in parallel, please follow: ' + 'https://docs.pinecone.io/docs/insert-data#sending-upserts-in-parallel') + if batch_size is None: return self._upsert_batch(vectors, namespace, _check_type, **kwargs) elif kwargs.get('async_req', False): @@ -121,10 +126,11 @@ def upsert(self, pbar = tqdm(total=len(vectors), disable=not show_progress, desc='Upserted vectors') total_upserted = 0 for i in range(0, len(vectors), batch_size): - batch = vectors[i:i + batch_size] - batch_result = self._upsert_batch(batch, namespace, _check_type, **kwargs) + batch_result = self._upsert_batch(vectors[i:i + batch_size], namespace, _check_type, **kwargs) + pbar.update(batch_result.upserted_count) + # we can't use here pbar.n for the case show_progress=False total_upserted += batch_result.upserted_count - pbar.update(len(batch)) + return UpsertResponse(upserted_count=total_upserted) def _upsert_batch(self, @@ -135,7 +141,7 @@ def _upsert_batch(self, args_dict = self._parse_non_empty_args([('namespace', namespace)]) - def transform_upsert_vector(item: Union[Vector, Tuple]): + def _vector_transform(item: Union[Vector, Tuple]): if isinstance(item, Vector): return item if isinstance(item, tuple): @@ -145,7 +151,7 @@ def transform_upsert_vector(item: Union[Vector, Tuple]): return self._vector_api.upsert( UpsertRequest( - vectors=list(map(transform_upsert_vector, vectors)), + vectors=list(map(_vector_transform, vectors)), **args_dict, _check_type=_check_type, **{k: v for k, v in kwargs.items() if k not in _OPENAPI_ENDPOINT_PARAMS} diff --git a/tests/unit/test_grpc_index.py b/tests/unit/test_grpc_index.py index 74f4cdb51..3d1921675 100644 --- a/tests/unit/test_grpc_index.py +++ b/tests/unit/test_grpc_index.py @@ -1,8 +1,10 @@ +import pytest + import pinecone from core.utils import dict_to_proto_struct from pinecone import DescribeIndexStatsRequest from pinecone.core.grpc.protos.vector_service_pb2 import Vector, DescribeIndexStatsRequest, UpdateRequest, \ - UpsertRequest, FetchRequest, QueryRequest, DeleteRequest, QueryVector + UpsertRequest, FetchRequest, QueryRequest, DeleteRequest, QueryVector, UpsertResponse class TestGrpcIndex: @@ -75,6 +77,128 @@ def test_upsert_async_upsertInputVectorsAsync(self, mocker): namespace='ns'), timeout=None) + def test_upsert_vectorListIsMultiplyOfBatchSize_vectorsUpsertedInBatches(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True, + side_effect=lambda stub, upsert_request, timeout: UpsertResponse( + upserted_count=len(upsert_request.vectors))) + + result = self.index.upsert([Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1)), + Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2))], + namespace='ns', + batch_size=1, + show_progress=False) + self.index._wrap_grpc_call.assert_any_call( + self.index.stub.Upsert, + UpsertRequest( + vectors=[ + Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1))], + namespace='ns'), + timeout=None) + + self.index._wrap_grpc_call.assert_any_call( + self.index.stub.Upsert, + UpsertRequest( + vectors=[Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2))], + namespace='ns'), + timeout=None) + + assert result.upserted_count == 2 + + def test_upsert_vectorListNotMultiplyOfBatchSize_vectorsUpsertedInBatches(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True, + side_effect=lambda stub, upsert_request, timeout: UpsertResponse( + upserted_count=len(upsert_request.vectors))) + + result = self.index.upsert([Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1)), + Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2)), + Vector(id='vec3', values=self.vals1, metadata=dict_to_proto_struct(self.md1))], + namespace='ns', + batch_size=2) + self.index._wrap_grpc_call.assert_any_call( + self.index.stub.Upsert, + UpsertRequest( + vectors=[ + Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1)), + Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2))], + namespace='ns'), + timeout=None) + + self.index._wrap_grpc_call.assert_any_call( + self.index.stub.Upsert, + UpsertRequest( + vectors=[Vector(id='vec3', values=self.vals1, metadata=dict_to_proto_struct(self.md1))], + namespace='ns'), + timeout=None) + + assert result.upserted_count == 3 + + def test_upsert_vectorListSmallerThanBatchSize_vectorsUpsertedInBatches(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True, + side_effect=lambda stub, upsert_request, timeout: UpsertResponse( + upserted_count=len(upsert_request.vectors))) + + result = self.index.upsert([Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1)), + Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2))], + namespace='ns', + batch_size=5) + + self.index._wrap_grpc_call.assert_called_once_with( + self.index.stub.Upsert, + UpsertRequest( + vectors=[ + Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1)), + Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2))], + namespace='ns'), + timeout=None) + + assert result.upserted_count == 2 + + def test_upsert_tuplesList_vectorsUpsertedInBatches(self, mocker): + mocker.patch.object(self.index, '_wrap_grpc_call', autospec=True, + side_effect=lambda stub, upsert_request, timeout: UpsertResponse( + upserted_count=len(upsert_request.vectors))) + + result = self.index.upsert([('vec1', self.vals1, self.md1), + ('vec2', self.vals2, self.md2), + ('vec3', self.vals1, self.md1)], + namespace='ns', + batch_size=2) + self.index._wrap_grpc_call.assert_any_call( + self.index.stub.Upsert, + UpsertRequest( + vectors=[ + Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1)), + Vector(id='vec2', values=self.vals2, metadata=dict_to_proto_struct(self.md2))], + namespace='ns'), + timeout=None) + + self.index._wrap_grpc_call.assert_any_call( + self.index.stub.Upsert, + UpsertRequest( + vectors=[Vector(id='vec3', values=self.vals1, metadata=dict_to_proto_struct(self.md1))], + namespace='ns'), + timeout=None) + + assert result.upserted_count == 3 + + def test_upsert_batchSizeIsNotPositive_errorIsRaised(self): + with pytest.raises(ValueError, match='batch_size must be a positive integer'): + self.index.upsert([Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1))], + namespace='ns', + batch_size=0) + + with pytest.raises(ValueError, match='batch_size must be a positive integer'): + self.index.upsert([Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1))], + namespace='ns', + batch_size=-1) + + def test_upsert_useBatchSizeAndAsyncReq_valueErrorRaised(self): + with pytest.raises(ValueError, match='async_req is not supported when batch_size is provided.'): + self.index.upsert([Vector(id='vec1', values=self.vals1, metadata=dict_to_proto_struct(self.md1))], + namespace='ns', + batch_size=2, + async_req=True) + # endregion # region: query tests diff --git a/tests/unit/test_index.py b/tests/unit/test_index.py index f805c5415..6c89467aa 100644 --- a/tests/unit/test_index.py +++ b/tests/unit/test_index.py @@ -1,7 +1,9 @@ +import pytest + from pinecone.core.client.api_client import Endpoint import pinecone -from pinecone import DescribeIndexStatsRequest, ScoredVector, QueryResponse +from pinecone import DescribeIndexStatsRequest, ScoredVector, QueryResponse, UpsertResponse class TestRestIndex: @@ -85,6 +87,137 @@ def test_upsert_parallelUpsert_callUpsertParallel(self, mocker): async_req=True ) + def test_upsert_vectorListIsMultiplyOfBatchSize_vectorsUpsertedInBatches(self, mocker): + mocker.patch.object(self.index._vector_api, + 'upsert', + autospec=True, + side_effect=lambda upsert_request: UpsertResponse( + upserted_count=len(upsert_request.vectors))) + + result = self.index.upsert(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), + pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2)], + namespace='ns', + batch_size=1, + show_progress=False) + + self.index._vector_api.upsert.assert_any_call( + pinecone.UpsertRequest(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), + ], namespace='ns') + ) + + self.index._vector_api.upsert.assert_any_call( + pinecone.UpsertRequest(vectors=[ + pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2), + ], namespace='ns') + ) + + assert result.upserted_count == 2 + + def test_upsert_vectorListNotMultiplyOfBatchSize_vectorsUpsertedInBatches(self, mocker): + mocker.patch.object(self.index._vector_api, + 'upsert', + autospec=True, + side_effect=lambda upsert_request: UpsertResponse( + upserted_count=len(upsert_request.vectors))) + + result = self.index.upsert(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), + pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2), + pinecone.Vector(id='vec3', values=self.vals1, metadata=self.md1)], + namespace='ns', + batch_size=2) + + self.index._vector_api.upsert.assert_any_call( + pinecone.UpsertRequest(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), + pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2), + ], namespace='ns') + ) + + self.index._vector_api.upsert.assert_any_call( + pinecone.UpsertRequest(vectors=[ + pinecone.Vector(id='vec3', values=self.vals1, metadata=self.md1), + ], namespace='ns') + ) + + assert result.upserted_count == 3 + + def test_upsert_vectorListSmallerThanBatchSize_vectorsUpsertedInBatches(self, mocker): + mocker.patch.object(self.index._vector_api, + 'upsert', + autospec=True, + side_effect=lambda upsert_request: UpsertResponse( + upserted_count=len(upsert_request.vectors))) + + result = self.index.upsert(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), + pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2), + pinecone.Vector(id='vec3', values=self.vals1, metadata=self.md1)], + namespace='ns', + batch_size=5) + + self.index._vector_api.upsert.assert_called_once_with( + pinecone.UpsertRequest(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), + pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2), + pinecone.Vector(id='vec3', values=self.vals1, metadata=self.md1), + ], namespace='ns') + ) + + assert result.upserted_count == 3 + + def test_upsert_tuplesList_vectorsUpsertedInBatches(self, mocker): + mocker.patch.object(self.index._vector_api, + 'upsert', + autospec=True, + side_effect=lambda upsert_request: UpsertResponse( + upserted_count=len(upsert_request.vectors))) + + result = self.index.upsert(vectors= + [('vec1', self.vals1, self.md1), + ('vec2', self.vals2, self.md2), + ('vec3', self.vals1, self.md1)], + namespace='ns', + batch_size=2) + + self.index._vector_api.upsert.assert_any_call( + pinecone.UpsertRequest(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1), + pinecone.Vector(id='vec2', values=self.vals2, metadata=self.md2), + ], namespace='ns') + ) + + self.index._vector_api.upsert.assert_any_call( + pinecone.UpsertRequest(vectors=[ + pinecone.Vector(id='vec3', values=self.vals1, metadata=self.md1), + ], namespace='ns') + ) + + assert result.upserted_count == 3 + + def test_upsert_batchSizeIsNotPositive_errorIsRaised(self): + with pytest.raises(ValueError, match='batch_size must be a positive integer'): + self.index.upsert(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1)], + namespace='ns', + batch_size=0) + + with pytest.raises(ValueError, match='batch_size must be a positive integer'): + self.index.upsert(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1)], + namespace='ns', + batch_size=-1) + + def test_upsert_useBatchSizeAndAsyncReq_valueErrorRaised(self): + with pytest.raises(ValueError, match='async_req is not supported when batch_size is provided.'): + self.index.upsert(vectors=[ + pinecone.Vector(id='vec1', values=self.vals1, metadata=self.md1)], + namespace='ns', + batch_size=1, + async_req=True) + # endregion # region: query tests From f82f5e81f904eef32612b75dd7d993f1a746333f Mon Sep 17 00:00:00 2001 From: Amnon Catav Date: Sun, 1 Jan 2023 12:55:15 +0200 Subject: [PATCH 3/3] remove redundant code --- pinecone/index.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/pinecone/index.py b/pinecone/index.py index 2f8260ec0..b14b39e71 100644 --- a/pinecone/index.py +++ b/pinecone/index.py @@ -115,10 +115,6 @@ def upsert(self, if batch_size is None: return self._upsert_batch(vectors, namespace, _check_type, **kwargs) - elif kwargs.get('async_req', False): - raise ValueError('async_req is not supported when batch_size is provided.' - 'To upsert in parallel, please follow: ' - 'https://docs.pinecone.io/docs/insert-data#sending-upserts-in-parallel') if not isinstance(batch_size, int) or batch_size <= 0: raise ValueError('batch_size must be a positive integer')