pg.ddx.io pgvector/pgvector GitHub issues and pull requests
help / color / mirror / Atom feed[pgvector/pgvector] issue #711: Any way to tune dot product?
3+ messages / 2 participants
[nested] [flat]
* [pgvector/pgvector] issue #711: Any way to tune dot product?
@ 2024-11-10 05:40 "ivanstepanovftw (@ivanstepanovftw)" <noreply+ivanstepanovftw@github.com>
0 siblings, 0 replies; 3+ messages in thread
From: ivanstepanovftw (@ivanstepanovftw) @ 2024-11-10 05:40 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Is there a way to tune dot product or cosine similarity in medium sized (1024 dimensional vectors, 10 millions total) databases?
I am talking about queries like `SELECT SUM(embedding <#> '[1, 2, 3]') FROM items;` that cannot gain performance from indices like IVFFLAT or HNSW.
Here is the example for 2**17 (131072) items of vector shape 1024:
```sql
EXPLAIN ANALYZE SELECT SUM(embedding <#> '[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]') FROM items;
```
```
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------
Aggregate (cost=2930.08..2930.09 rows=1 width=8) (actual time=523.065..523.066 rows=1 loops=1)
-> Seq Scan on items (cost=0.00..2274.72 rows=131072 width=18) (actual time=0.062..8.157 rows=131072 loops=1)
Planning Time: 0.070 ms
Execution Time: 523.116 ms
(4 rows)
```
I have tried to retrieve embeddings and calculate dot product by using torch/numpy/numba+numpy, but it is even a magnitude slower (like 33 times slower) than using DB query.
Here is what I am dealing with
```python
import asyncio
import time
import numba
import numpy as np
from pgvector.sqlalchemy import Vector
from sqlalchemy import Column, BigInteger, func
from sqlalchemy import select
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import declarative_base, sessionmaker, Mapped, mapped_column
# Define database connection details
DATABASE_URL = "postgresql+asyncpg://postgres@/postgres"
# Initialize the SQLAlchemy async engine
engine = create_async_engine(DATABASE_URL, echo=False, future=True)
# Define the ORM base and the items table
Base = declarative_base()
class Item(Base):
__tablename__ = "items"
id = Column(BigInteger, primary_key=True, autoincrement=True)
embedding: Mapped[np.ndarray | None] = mapped_column(Vector(1024), nullable=True)
# Initialize the sessionmaker
async_session = sessionmaker(
engine, expire_on_commit=False, class_=AsyncSession
)
# Generate data: Number of items and dimensions
num_items = 2**17
vector_dimension = 1024
batch_size = 2**15
class Stopwatch:
def __init__(self, name: str):
self.name = name
@staticmethod
def time():
return time.perf_counter()
def __enter__(self):
self.start = self.time()
return self
def __exit__(self, type, value, traceback):
self.end = self.time()
@property
def duration(self):
end = self.end if hasattr(self, "end") else self.time()
return end - self.start
def __str__(self):
return f"{self.name}: {self.duration:.3f} s"
def __repr__(self):
return str(self)
@numba.jit
def aggdot(a, b):
return np.sum(np.dot(a, b))
async def test_avg(np_embeddings):
# Select all embeddings to calculate sum of all distances to a zero vector
embedding = np.zeros(vector_dimension).astype(np.float32)
embedding[-1] = 1
async with async_session() as session:
async with session.begin():
with Stopwatch("Query") as s:
result = (
await session.execute(
select(
func.sum(Item.embedding.max_inner_product(embedding))
)
)
).scalar()
print(f"{s=}")
print(f"{result=}")
print('-'*40)
cumsum = 0
async with async_session() as session:
async with session.begin():
with Stopwatch("Query") as s:
for i in range(0, num_items, batch_size):
results = await session.execute(
select(
Item.embedding
)
.offset(i)
.limit(batch_size)
)
embeddings = results.fetchall() # or results.all()
embeddings = np.asarray([item.embedding for item in embeddings])
cumsum += np.sum(np.dot(embeddings, embedding))
print(f"{s=}")
print(f"{cumsum=}") # should be -65526.48813415579
# Without SQL at all
print('-'*40)
with Stopwatch("Numpy") as s:
embedding = np.random.rand(vector_dimension).astype(np.float32)
cumsum = np.sum(np.dot(embeddings, embedding))
print(f"{s=}")
print(f"{cumsum=}")
# With jit
print('-'*40)
with Stopwatch("Numba") as s:
embedding = np.random.rand(vector_dimension).astype(np.float32)
cumsum = aggdot(embeddings, embedding)
print(f"{s=}")
print(f"{cumsum=}")
print('='*80)
async def main_measure_performance():
np_embeddings = np.random.rand(num_items, vector_dimension).astype(np.float32)
for _ in range(10):
await test_avg(np_embeddings)
if __name__ == '__main__':
asyncio.run(main_measure_performance())
"""
s=Query: 0.584 s
result=-65526.48813415579
----------------------------------------
s=Query: 19.354 s
cumsum=np.float32(65526.49)
----------------------------------------
s=Numpy: 0.007 s
cumsum=np.float32(8303207.0)
----------------------------------------
s=Numba: 0.736 s
cumsum=8097196.0
================================================================================
s=Query: 0.554 s
result=-65526.48813415579
----------------------------------------
s=Query: 18.791 s
cumsum=np.float32(65526.49)
----------------------------------------
s=Numpy: 0.006 s
cumsum=np.float32(8543588.0)
----------------------------------------
s=Numba: 0.015 s
cumsum=8316169.0
================================================================================
s=Query: 0.555 s
result=-65526.48813415579
----------------------------------------
s=Query: 18.978 s
cumsum=np.float32(65526.49)
----------------------------------------
s=Numpy: 0.008 s
cumsum=np.float32(8304899.5)
----------------------------------------
s=Numba: 0.023 s
cumsum=8285002.5
================================================================================
...
"""
```
Of course numpy uses multiple threads in `np.dot` call. In Postgres, setting more threads does not help much with the provided query and it still uses 1 or 2 workers.
^ permalink raw [nested|flat] 3+ messages in thread
* Re: [pgvector/pgvector] issue #711: Any way to tune dot product?
@ 2024-11-10 08:39 ` "ankane (@ankane)" <noreply+ankane@github.com>
1 sibling, 0 replies; 3+ messages in thread
From: ankane (@ankane) @ 2024-11-10 08:39 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Check out the docs for advice on [tuning Postgres](https://github.com/pgvector/pgvector?tab=readme-ov-file#tuning). In general, libraries like NumPy that store vectors in contiguous memory and use matrix multiplication will have better performance for this type of query.
^ permalink raw [nested|flat] 3+ messages in thread
* Re: [pgvector/pgvector] issue #711: Any way to tune dot product?
@ 2024-11-10 08:39 ` "ankane (@ankane)" <noreply+ankane@github.com>
1 sibling, 0 replies; 3+ messages in thread
From: ankane (@ankane) @ 2024-11-10 08:39 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
@ankane closed this.
^ permalink raw [nested|flat] 3+ messages in thread
end of thread, other threads:[~2024-11-10 08:39 UTC | newest]
Thread overview: 3+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2024-11-10 05:40 [pgvector/pgvector] issue #711: Any way to tune dot product? "ivanstepanovftw (@ivanstepanovftw)" <noreply+ivanstepanovftw@github.com>
2024-11-10 08:39 ` "ankane (@ankane)" <noreply+ankane@github.com>
2024-11-10 08:39 ` "ankane (@ankane)" <noreply+ankane@github.com>
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox