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

Fix potential edge case scoring in context search #474

Merged
merged 4 commits into from
Feb 8, 2024
Merged
Changes from 2 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
18 changes: 14 additions & 4 deletions qdrant_client/local/distances.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,13 +147,21 @@ def calculate_distance_core(
return calculate_distance(query, vectors, distance_type)


def fast_sigmoid(x: np.float32) -> np.float32:
if not np.isfinite(x):
Copy link
Member

Choose a reason for hiding this comment

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

I am a bit confused by it, I know, that we have had such a check for quite some time now though..

Do we wait for a particular not finite type here?

Like -inf, +inf, nan ? (if we wait -inf, won't it be better to return a constant value?)

It seems for me that at the moment, If vector has a non-finite difference with any of context pairs, then it is excluded from result search, because it will have non-finite score in overall_scores

Copy link

Choose a reason for hiding this comment

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

Yeah, I don't know if I understand well, but if x equal +inf or -inf the function return x is good or you want to return for example 2 or 3 ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

You're right, in those cases we should return the limit of the function, which should be -1 or +1

# To avoid NaNs, which gets: RuntimeWarning: invalid value encountered in scalar divide
return x

return x / (1.0 + abs(x))


def scaled_fast_sigmoid(x: np.float32) -> np.float32:
if np.isfinite(x):
return 0.5 * (x / (1.0 + abs(x)) + 1.0)
else:
if not np.isfinite(x):
# To avoid NaNs, which gets: RuntimeWarning: invalid value encountered in scalar divide
return x

return 0.5 * (x / (1.0 + abs(x)) + 1.0)


def calculate_recommend_best_scores(
query: RecoQuery, vectors: types.NumpyArray, distance_type: models.Distance
Expand Down Expand Up @@ -234,7 +242,9 @@ def calculate_context_scores(
neg = calculate_distance_core(pair.negative, vectors, distance_type)

difference = pos - neg - EPSILON
pair_scores = np.minimum(difference, 0.0)
pair_scores = np.fromiter(
(fast_sigmoid(xi) for xi in np.minimum(difference, 0.0)), np.float32
)
overall_scores += pair_scores

return overall_scores
Expand Down
Loading