langchain/libs/community/tests/unit_tests/utils/test_math.py
Joydeep Banik Roy 3796672c67
community, milvus, pinecone, qdrant, mongo: Broadcast operation failure while using simsimd beyond v3.7.7 (#22271)
- [ ] **Packages affected**: 
  - community: fix `cosine_similarity` to support simsimd beyond 3.7.7
- partners/milvus: fix `cosine_similarity` to support simsimd beyond
3.7.7
- partners/mongodb: fix `cosine_similarity` to support simsimd beyond
3.7.7
- partners/pinecone: fix `cosine_similarity` to support simsimd beyond
3.7.7
- partners/qdrant: fix `cosine_similarity` to support simsimd beyond
3.7.7


- [ ] **Broadcast operation failure while using simsimd beyond v3.7.7**:
- **Description:** I was using simsimd 4.3.1 and the unsupported operand
type issue popped up. When I checked out the repo and ran the tests,
they failed as well (have attached a screenshot for that). Looks like it
is a variant of https://github.com/langchain-ai/langchain/issues/18022 .
Prior to 3.7.7, simd.cdist returned an ndarray but now it returns
simsimd.DistancesTensor which is ineligible for a broadcast operation
with numpy. With this change, it also remove the need to explicitly cast
`Z` to numpy array
    - **Issue:** #19905
    - **Dependencies:** No
    - **Twitter handle:** https://x.com/GetzJoydeep

<img width="1622" alt="Screenshot 2024-05-29 at 2 50 00 PM"
src="https://github.com/langchain-ai/langchain/assets/31132555/fb27b383-a9ae-4a6f-b355-6d503b72db56">

- [ ] **Considerations**: 
1. I started with community but since similar changes were there in
Milvus, MongoDB, Pinecone, and QDrant so I modified their files as well.
If touching multiple packages in one PR is not the norm, then I can
remove them from this PR and raise separate ones
2. I have run and verified that the tests work. Since, only MongoDB had
tests, I ran theirs and verified it works as well. Screenshots attached
:
<img width="1573" alt="Screenshot 2024-05-29 at 2 52 13 PM"
src="https://github.com/langchain-ai/langchain/assets/31132555/ce87d1ea-19b6-4900-9384-61fbc1a30de9">
<img width="1614" alt="Screenshot 2024-05-29 at 3 33 51 PM"
src="https://github.com/langchain-ai/langchain/assets/31132555/6ce1d679-db4c-4291-8453-01028ab2dca5">
  

I have added a test for simsimd. I feel it may not go well with the
CI/CD setup as installing simsimd is not a dependency requirement. I
have just imported simsimd to ensure simsimd cosine similarity is
invoked. However, its not a good approach. Suggestions are welcome and I
can make the required changes on the PR. Please provide guidance on the
same as I am new to the community.

---------

Co-authored-by: Bagatur <baskaryan@gmail.com>
Co-authored-by: Bagatur <22008038+baskaryan@users.noreply.github.com>
2024-06-04 17:36:31 +00:00

96 lines
3.1 KiB
Python

"""Test math utility functions."""
import importlib
from typing import List
import numpy as np
import pytest
from langchain_community.utils.math import cosine_similarity, cosine_similarity_top_k
@pytest.fixture
def X() -> List[List[float]]:
return [[1.0, 2.0, 3.0], [0.0, 1.0, 0.0], [1.0, 2.0, 0.0]]
@pytest.fixture
def Y() -> List[List[float]]:
return [[0.5, 1.0, 1.5], [1.0, 0.0, 0.0], [2.0, 5.0, 2.0], [0.0, 0.0, 0.0]]
def test_cosine_similarity_zero() -> None:
X = np.zeros((3, 3))
Y = np.random.random((3, 3))
expected = np.zeros((3, 3))
actual = cosine_similarity(X, Y)
assert np.allclose(expected, actual)
def test_cosine_similarity_identity() -> None:
X = np.random.random((4, 4))
expected = np.ones(4)
actual = np.diag(cosine_similarity(X, X))
assert np.allclose(expected, actual)
def test_cosine_similarity_empty() -> None:
empty_list: List[List[float]] = []
assert len(cosine_similarity(empty_list, empty_list)) == 0
assert len(cosine_similarity(empty_list, np.random.random((3, 3)))) == 0
def test_cosine_similarity(X: List[List[float]], Y: List[List[float]]) -> None:
expected = [
[1.0, 0.26726124, 0.83743579, 0.0],
[0.53452248, 0.0, 0.87038828, 0.0],
[0.5976143, 0.4472136, 0.93419873, 0.0],
]
actual = cosine_similarity(X, Y)
assert np.allclose(expected, actual)
def test_cosine_similarity_top_k(X: List[List[float]], Y: List[List[float]]) -> None:
expected_idxs = [(0, 0), (2, 2), (1, 2), (0, 2), (2, 0)]
expected_scores = [1.0, 0.93419873, 0.87038828, 0.83743579, 0.5976143]
actual_idxs, actual_scores = cosine_similarity_top_k(X, Y)
assert actual_idxs == expected_idxs
assert np.allclose(expected_scores, actual_scores)
def test_cosine_similarity_score_threshold(
X: List[List[float]], Y: List[List[float]]
) -> None:
expected_idxs = [(0, 0), (2, 2)]
expected_scores = [1.0, 0.93419873]
actual_idxs, actual_scores = cosine_similarity_top_k(
X, Y, top_k=None, score_threshold=0.9
)
assert actual_idxs == expected_idxs
assert np.allclose(expected_scores, actual_scores)
def invoke_cosine_similarity_top_k_score_threshold(
X: List[List[float]], Y: List[List[float]]
) -> None:
expected_idxs = [(0, 0), (2, 2), (1, 2), (0, 2)]
expected_scores = [1.0, 0.93419873, 0.87038828, 0.83743579]
actual_idxs, actual_scores = cosine_similarity_top_k(X, Y, score_threshold=0.8)
assert actual_idxs == expected_idxs
assert np.allclose(expected_scores, actual_scores)
def test_cosine_similarity_top_k_and_score_threshold(
X: List[List[float]], Y: List[List[float]]
) -> None:
if importlib.util.find_spec("simsimd"):
raise ValueError("test should be run without simsimd installed.")
invoke_cosine_similarity_top_k_score_threshold(X, Y)
@pytest.mark.requires("simsimd")
def test_cosine_similarity_top_k_and_score_threshold_with_simsimd(
X: List[List[float]], Y: List[List[float]]
) -> None:
# Same test, but ensuring simsimd is available in the project through the import.
invoke_cosine_similarity_top_k_score_threshold(X, Y)