Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update HNSW indexes to use cosine operator #155

Merged
merged 2 commits into from
Jan 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/app-tests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ jobs:
if: matrix.os == 'ubuntu-latest'
run: |
sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y
sudo apt-get install postgresql-14-pgvector
sudo apt-get install postgresql-16-pgvector
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It failed with 14 on ubuntu-latest runner

sudo systemctl start postgresql
sudo -u postgres psql -c "ALTER USER ${{ env.POSTGRES_USERNAME }} PASSWORD '${{ env.POSTGRES_PASSWORD }}'"
sudo -u postgres psql -c 'CREATE EXTENSION vector'
Expand Down
19 changes: 13 additions & 6 deletions src/backend/fastapi_app/postgres_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,23 +39,30 @@ def to_str_for_embedding(self):
return f"Name: {self.name} Description: {self.description} Type: {self.type}"


# Define HNSW index to support vector similarity search
# Use the vector_ip_ops access method (inner product) since these embeddings are normalized
"""
**Define HNSW index to support vector similarity search**

We use the vector_cosine_ops access method (cosine distance)
since it works for both normalized and non-normalized vector embeddings
If you know your embeddings are normalized,
you can switch to inner product for potentially better performance.
The index operator should match the operator used in queries.
"""

table_name = Item.__tablename__

index_ada002 = Index(
"hnsw_index_for_innerproduct_{table_name}_embedding_ada002",
"hnsw_index_for_cosine_{table_name}_embedding_ada002",
Item.embedding_ada002,
postgresql_using="hnsw",
postgresql_with={"m": 16, "ef_construction": 64},
postgresql_ops={"embedding_ada002": "vector_ip_ops"},
postgresql_ops={"embedding_ada002": "vector_cosine_ops"},
)

index_nomic = Index(
f"hnsw_index_for_innerproduct_{table_name}_embedding_nomic",
f"hnsw_index_for_cosine_{table_name}_embedding_nomic",
Item.embedding_nomic,
postgresql_using="hnsw",
postgresql_with={"m": 16, "ef_construction": 64},
postgresql_ops={"embedding_nomic": "vector_ip_ops"},
postgresql_ops={"embedding_nomic": "vector_cosine_ops"},
)
Loading