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 normalize_embedding using numba #2347

Merged
merged 3 commits into from
Mar 22, 2022
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: 0 additions & 2 deletions docs/_src/api/api/document_store.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,8 +212,6 @@ TODO drop params
#### normalize\_embedding

```python
@staticmethod
@njit
def normalize_embedding(emb: np.ndarray) -> None
```

Expand Down
30 changes: 19 additions & 11 deletions haystack/document_stores/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,9 +341,7 @@ def get_document_count(
) -> int:
pass

@staticmethod
@njit # (fastmath=True)
def normalize_embedding(emb: np.ndarray) -> None:
def normalize_embedding(self, emb: np.ndarray) -> None:
"""
Performs L2 normalization of embeddings vector inplace. Input can be a single vector (1D array) or a matrix
(2D array).
Expand All @@ -352,16 +350,26 @@ def normalize_embedding(emb: np.ndarray) -> None:

# Single vec
if len(emb.shape) == 1:
norm = np.sqrt(emb.dot(emb)) # faster than np.linalg.norm()
if norm != 0.0:
emb /= norm
self._normalize_embedding_1D(emb)
# 2D matrix
else:
for vec in emb:
vec = np.ascontiguousarray(vec)
norm = np.sqrt(vec.dot(vec))
if norm != 0.0:
vec /= norm
self._normalize_embedding_2D(emb)

@staticmethod
@njit # (fastmath=True)
def _normalize_embedding_1D(emb: np.ndarray) -> None:
norm = np.sqrt(emb.dot(emb)) # faster than np.linalg.norm()
if norm != 0.0:
emb /= norm

@staticmethod
@njit # (fastmath=True)
def _normalize_embedding_2D(emb: np.ndarray) -> None:
for vec in emb:
vec = np.ascontiguousarray(vec)
norm = np.sqrt(vec.dot(vec))
if norm != 0.0:
vec /= norm

def finalize_raw_score(self, raw_score: float, similarity: Optional[str]) -> float:
if similarity == "cosine":
Expand Down