-
Notifications
You must be signed in to change notification settings - Fork 52
Add option to normalize vector distances on query #298
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
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,6 +5,7 @@ | |
|
||
from redisvl.query.filter import FilterExpression | ||
from redisvl.redis.utils import array_to_buffer | ||
from redisvl.utils.utils import denorm_cosine_distance | ||
|
||
|
||
class BaseQuery(RedisQuery): | ||
|
@@ -175,6 +176,8 @@ class BaseVectorQuery: | |
DISTANCE_ID: str = "vector_distance" | ||
VECTOR_PARAM: str = "vector" | ||
|
||
_normalize_vector_distance: bool = False | ||
|
||
|
||
class HybridPolicy(str, Enum): | ||
"""Enum for valid hybrid policy options in vector queries.""" | ||
|
@@ -198,6 +201,7 @@ def __init__( | |
in_order: bool = False, | ||
hybrid_policy: Optional[str] = None, | ||
batch_size: Optional[int] = None, | ||
normalize_vector_distance: bool = False, | ||
): | ||
"""A query for running a vector search along with an optional filter | ||
expression. | ||
|
@@ -233,6 +237,12 @@ def __init__( | |
of vectors to fetch in each batch. Larger values may improve performance | ||
at the cost of memory usage. Only applies when hybrid_policy="BATCHES". | ||
Defaults to None, which lets Redis auto-select an appropriate batch size. | ||
normalize_vector_distance (bool): Redis supports 3 distance metrics: L2 (euclidean), | ||
IP (inner product), and COSINE. By default, L2 distance returns an unbounded value. | ||
COSINE distance returns a value between 0 and 2. IP returns a value determined by | ||
the magnitude of the vector. Setting this flag to true converts COSINE and L2 distance | ||
to a similarity score between 0 and 1. Note: setting this flag to true for IP will | ||
throw a warning since by definition COSINE similarity is normalized IP. | ||
|
||
Raises: | ||
TypeError: If filter_expression is not of type redisvl.query.FilterExpression | ||
|
@@ -246,6 +256,7 @@ def __init__( | |
self._num_results = num_results | ||
self._hybrid_policy: Optional[HybridPolicy] = None | ||
self._batch_size: Optional[int] = None | ||
self._normalize_vector_distance = normalize_vector_distance | ||
self.set_filter(filter_expression) | ||
query_string = self._build_query_string() | ||
|
||
|
@@ -394,6 +405,7 @@ def __init__( | |
in_order: bool = False, | ||
hybrid_policy: Optional[str] = None, | ||
batch_size: Optional[int] = None, | ||
normalize_vector_distance: bool = False, | ||
): | ||
"""A query for running a filtered vector search based on semantic | ||
distance threshold. | ||
|
@@ -437,6 +449,19 @@ def __init__( | |
of vectors to fetch in each batch. Larger values may improve performance | ||
at the cost of memory usage. Only applies when hybrid_policy="BATCHES". | ||
Defaults to None, which lets Redis auto-select an appropriate batch size. | ||
normalize_vector_distance (bool): Redis supports 3 distance metrics: L2 (euclidean), | ||
IP (inner product), and COSINE. By default, L2 distance returns an unbounded value. | ||
COSINE distance returns a value between 0 and 2. IP returns a value determined by | ||
the magnitude of the vector. Setting this flag to true converts COSINE and L2 distance | ||
to a similarity score between 0 and 1. Note: setting this flag to true for IP will | ||
throw a warning since by definition COSINE similarity is normalized IP. | ||
|
||
Raises: | ||
TypeError: If filter_expression is not of type redisvl.query.FilterExpression | ||
|
||
Note: | ||
Learn more about vector range queries: https://redis.io/docs/interact/search-and-query/search/vectors/#range-query | ||
|
||
""" | ||
self._vector = vector | ||
self._vector_field_name = vector_field_name | ||
|
@@ -456,6 +481,7 @@ def __init__( | |
if batch_size is not None: | ||
self.set_batch_size(batch_size) | ||
|
||
self._normalize_vector_distance = normalize_vector_distance | ||
self.set_distance_threshold(distance_threshold) | ||
self.set_filter(filter_expression) | ||
query_string = self._build_query_string() | ||
|
@@ -493,6 +519,14 @@ def set_distance_threshold(self, distance_threshold: float): | |
raise TypeError("distance_threshold must be of type float or int") | ||
if distance_threshold < 0: | ||
raise ValueError("distance_threshold must be non-negative") | ||
if self._normalize_vector_distance: | ||
if distance_threshold > 1: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nice! |
||
raise ValueError( | ||
"distance_threshold must be between 0 and 1 when normalize_vector_distance is set to True" | ||
) | ||
|
||
# User sets normalized value 0-1 denormalize for use in DB | ||
distance_threshold = denorm_cosine_distance(distance_threshold) | ||
self._distance_threshold = distance_threshold | ||
|
||
# Reset the query string | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -191,3 +191,22 @@ def wrapper(): | |
return | ||
|
||
return wrapper | ||
|
||
|
||
def norm_cosine_distance(value: float) -> float: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could add additional check logic to this function kept it simple stupid to start |
||
""" | ||
Normalize the cosine distance to a similarity score between 0 and 1. | ||
""" | ||
return max((2 - value) / 2, 0) | ||
|
||
|
||
def denorm_cosine_distance(value: float) -> float: | ||
"""Denormalize the distance threshold from [0, 1] to [0, 1] for our db.""" | ||
return max(2 - 2 * value, 0) | ||
|
||
|
||
def norm_l2_distance(value: float) -> float: | ||
""" | ||
Normalize the L2 distance. | ||
""" | ||
return 1 / (1 + value) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.