| """ |
| Test basic functionality of BGE embedder models with Transformers v5. |
| |
| This test loads a small/public BGE checkpoint and runs a single encode on toy strings, |
| verifying that the shape/dtype are correct and that cosine similarity is sane. |
| """ |
| import pytest |
| import torch |
| import numpy as np |
| from FlagEmbedding import FlagModel |
|
|
| def cosine_similarity(a, b): |
| """Compute cosine similarity between two vectors.""" |
| return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)) |
|
|
| def test_bge_embedder_basic(device): |
| """Test basic functionality of BGE embedder.""" |
| |
| model_name = "BAAI/bge-base-en-v1.5" |
| model = FlagModel(model_name, device=device) |
| |
| |
| query = "What is the capital of France?" |
| passage = "Paris is the capital and most populous city of France." |
| |
| |
| query_embedding = model.encode(query) |
| passage_embedding = model.encode(passage) |
| |
| |
| assert isinstance(query_embedding, np.ndarray) |
| assert isinstance(passage_embedding, np.ndarray) |
| assert query_embedding.ndim == 1 |
| assert passage_embedding.ndim == 1 |
| |
| |
| assert not np.isnan(query_embedding).any() |
| assert not np.isnan(passage_embedding).any() |
| |
| |
| similarity = cosine_similarity(query_embedding, passage_embedding) |
| assert 0 <= similarity <= 1 |
| assert similarity > 0.5 |
|
|
| def test_bge_embedder_batch(device): |
| """Test batch encoding with BGE embedder.""" |
| |
| model_name = "BAAI/bge-base-en-v1.5" |
| model = FlagModel(model_name, device=device) |
| |
| |
| queries = [ |
| "What is the capital of France?", |
| "Who wrote Romeo and Juliet?" |
| ] |
| |
| |
| embeddings = model.encode(queries) |
| |
| |
| assert isinstance(embeddings, np.ndarray) |
| assert embeddings.ndim == 2 |
| assert embeddings.shape[0] == len(queries) |
| |
| |
| assert not np.isnan(embeddings).any() |