-
Notifications
You must be signed in to change notification settings - Fork 1.9k
[TST] Add local_simple_hash embedding, tests, docs, and example #5732
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
Open
Himanshu7921
wants to merge
4
commits into
chroma-core:main
Choose a base branch
from
Himanshu7921:feat/local-simple-hash-tests
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
b92d4bc
DOC: add Windows Python-only dev setup and example notebook
Himanshu7921 7a81824
[TST] Add local_simple_hash embedding, tests, docs, and example
Himanshu7921 b345267
Merge branch 'main' into feat/local-simple-hash-tests
Himanshu7921 14681df
Update chromadb/utils/embedding_functions/simple_hash_embedding_funct…
Himanshu7921 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| import numpy as np | ||
| import pytest | ||
|
|
||
| from chromadb.utils.embedding_functions.simple_hash_embedding_function import ( | ||
| SimpleHashEmbeddingFunction, | ||
| ) | ||
| from chromadb.utils.embedding_functions import config_to_embedding_function | ||
|
|
||
|
|
||
| def test_simple_hash_basic() -> None: | ||
| ef = SimpleHashEmbeddingFunction(dim=16) | ||
|
|
||
| docs = ["hello", "world", ""] | ||
| embeddings = ef(docs) | ||
|
|
||
| assert isinstance(embeddings, list) | ||
| assert len(embeddings) == 3 | ||
|
|
||
| # first two should be non-zero, third (empty string) should be zero vector | ||
| assert isinstance(embeddings[0], np.ndarray) | ||
| assert embeddings[0].dtype == np.float32 | ||
| assert embeddings[0].shape == (16,) | ||
| assert np.linalg.norm(embeddings[0]) > 0 | ||
| assert np.linalg.norm(embeddings[1]) > 0 | ||
| assert np.allclose(embeddings[2], np.zeros(16, dtype=np.float32)) | ||
|
|
||
|
|
||
| def test_embed_query_and_determinism() -> None: | ||
| ef = SimpleHashEmbeddingFunction(dim=8) | ||
| q = ["test query"] | ||
| a = ef(q) | ||
| b = ef.embed_query(q) | ||
| # same content -> same embedding | ||
| assert len(a) == len(b) == 1 | ||
| assert np.allclose(a[0], b[0]) | ||
|
|
||
| # deterministic across calls | ||
| c = ef(["test query"]) | ||
| assert np.allclose(a[0], c[0]) | ||
|
|
||
|
|
||
| def test_config_integration() -> None: | ||
| cfg = {"name": "local_simple_hash", "config": {"dim": 12}} | ||
| ef = config_to_embedding_function(cfg) | ||
| assert isinstance(ef, SimpleHashEmbeddingFunction) | ||
| out = ef(["x"]) | ||
| assert len(out) == 1 and out[0].shape == (12,) | ||
|
|
||
|
|
||
| def test_edge_cases_long_and_non_string_inputs() -> None: | ||
| ef = SimpleHashEmbeddingFunction(dim=20) | ||
|
|
||
| # Very long string should produce a stable vector and not error | ||
| long_text = "a" * 10000 | ||
| long_emb = ef([long_text])[0] | ||
| assert long_emb.shape == (20,) | ||
| assert np.linalg.norm(long_emb) > 0 | ||
|
|
||
| # Non-string inputs should be accepted and converted via str() | ||
| samples = [123, None, 45.6, b"bytes"] | ||
| # Convert samples to strings before passing to the embedding function to satisfy typing | ||
| stringified = [str(s) for s in samples] | ||
| emb = ef(stringified) | ||
| assert len(emb) == 4 | ||
| for v in emb: | ||
| assert isinstance(v, np.ndarray) | ||
| assert v.shape == (20,) | ||
|
|
||
| # Empty input list is not allowed at the public API layer; wrapper validates non-empty | ||
| with pytest.raises(ValueError): | ||
| ef([]) |
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
79 changes: 79 additions & 0 deletions
79
chromadb/utils/embedding_functions/simple_hash_embedding_function.py
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 |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| from typing import List, Dict, Any | ||
|
|
||
| import numpy as np | ||
|
|
||
| from chromadb.api.types import EmbeddingFunction, Embeddings, Documents, Space | ||
|
|
||
|
|
||
| class SimpleHashEmbeddingFunction(EmbeddingFunction[Documents]): | ||
| """A tiny, dependency-free local embedding function used for tests and examples. | ||
|
|
||
| It deterministically converts each input string into a fixed-size float32 vector | ||
| by hashing character codes. This is intentionally simple so it works in CI | ||
| without external model or network dependencies. | ||
| """ | ||
|
|
||
| def __init__(self, dim: int = 32): | ||
| if dim <= 0: | ||
| raise ValueError("dim must be a positive integer") | ||
|
|
||
| self.dim = int(dim) | ||
|
|
||
| def _embed_one(self, text: str) -> np.ndarray: | ||
| # Simple deterministic embedding: accumulate character ordinals into a fixed-size vector | ||
| v = np.zeros(self.dim, dtype=np.float32) | ||
| if not text: | ||
| return v | ||
|
|
||
| for i, ch in enumerate(text): | ||
| idx = i % self.dim | ||
| v[idx] += (ord(ch) % 256) / 256.0 | ||
|
|
||
| # Normalize to unit length to be more embedding-like | ||
| norm = np.linalg.norm(v) | ||
| if norm > 0: | ||
| v = v / norm | ||
|
|
||
| return v | ||
|
|
||
| def __call__(self, input: Documents) -> Embeddings: | ||
| if not input: | ||
| return [] | ||
|
|
||
| return [self._embed_one(str(d)) for d in list(input)] | ||
|
|
||
| def embed_query(self, input: Documents) -> Embeddings: | ||
| # For this simple embedding, queries use the same function | ||
| return self.__call__(input) | ||
|
|
||
| @staticmethod | ||
| def name() -> str: | ||
| return "local_simple_hash" | ||
|
|
||
| def default_space(self) -> Space: | ||
| return "cosine" | ||
|
|
||
| def supported_spaces(self) -> List[Space]: | ||
| return ["cosine", "l2", "ip"] | ||
|
|
||
| @staticmethod | ||
| def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": | ||
| dim = config.get("dim", 32) | ||
| return SimpleHashEmbeddingFunction(dim=dim) | ||
|
|
||
| def get_config(self) -> Dict[str, Any]: | ||
| return {"dim": self.dim} | ||
|
|
||
| def validate_config_update( | ||
| self, old_config: Dict[str, Any], new_config: Dict[str, Any] | ||
| ) -> None: | ||
| # Changing dim is allowed for this toy function | ||
| return | ||
|
|
||
| @staticmethod | ||
| def validate_config(config: Dict[str, Any]) -> None: | ||
| # Very small validation | ||
| if "dim" in config: | ||
| dim = config["dim"] | ||
| if not isinstance(dim, int) or dim <= 0: | ||
| raise ValueError("dim must be a positive integer") | ||
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.