-
Notifications
You must be signed in to change notification settings - Fork 85
feat: Add memory-efficient embed_stream method for large datasets #698
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
fede-kamel
wants to merge
4
commits into
cohere-ai:main
Choose a base branch
from
fede-kamel:feature/memory-efficient-embed-streaming
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 all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
4710b8a
Add memory-efficient embed_stream method
80a9acb
feat: Add memory-efficient embed_stream method for processing large d…
101d3db
fix: Address review feedback for embed_stream
fede-kamel 06a9eb0
refactor(embed_stream): move to manually maintained files, fix magic …
fede-kamel 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,2 @@ | ||
| embed_batch_size = 96 | ||
| embed_stream_batch_size = 96 # Max texts per API request (API limit) |
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,74 @@ | ||
| """Utilities for streaming embed responses without loading all embeddings into memory.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from dataclasses import dataclass | ||
| from typing import Iterator, List, Optional, Union | ||
|
|
||
|
|
||
| @dataclass | ||
| class StreamedEmbedding: | ||
| """A single embedding yielded incrementally from embed_stream().""" | ||
| index: int | ||
| embedding: Union[List[float], List[int]] | ||
| embedding_type: str | ||
| text: Optional[str] = None | ||
|
|
||
|
|
||
| def extract_embeddings_from_response( | ||
| response_data: dict, | ||
| batch_texts: List[str], | ||
| global_offset: int = 0, | ||
| ) -> Iterator[StreamedEmbedding]: | ||
| """ | ||
| Extract individual embeddings from a Cohere embed response dict. | ||
|
|
||
| Works for both V1 (embeddings_floats / embeddings_by_type) and V2 response formats. | ||
|
|
||
| Args: | ||
| response_data: Parsed JSON response from embed endpoint | ||
| batch_texts: The texts that were embedded in this batch | ||
| global_offset: Starting index for this batch within the full dataset | ||
|
|
||
| Yields: | ||
| StreamedEmbedding objects | ||
| """ | ||
| response_type = response_data.get("response_type", "") | ||
|
|
||
| if response_type == "embeddings_floats": | ||
| embeddings = response_data.get("embeddings", []) | ||
| for i, embedding in enumerate(embeddings): | ||
| yield StreamedEmbedding( | ||
| index=global_offset + i, | ||
| embedding=embedding, | ||
| embedding_type="float", | ||
| text=batch_texts[i] if i < len(batch_texts) else None, | ||
| ) | ||
|
|
||
| elif response_type == "embeddings_by_type": | ||
| embeddings_obj = response_data.get("embeddings", {}) | ||
| for emb_type, embeddings_list in embeddings_obj.items(): | ||
| type_name = emb_type.rstrip("_") | ||
| if isinstance(embeddings_list, list): | ||
| for i, embedding in enumerate(embeddings_list): | ||
| yield StreamedEmbedding( | ||
| index=global_offset + i, | ||
| embedding=embedding, | ||
| embedding_type=type_name, | ||
| text=batch_texts[i] if i < len(batch_texts) else None, | ||
| ) | ||
|
|
||
| else: | ||
| # V2 format: embeddings is a dict with type keys directly | ||
| embeddings_obj = response_data.get("embeddings", {}) | ||
| if isinstance(embeddings_obj, dict): | ||
| for emb_type, embeddings_list in embeddings_obj.items(): | ||
| type_name = emb_type.rstrip("_") | ||
| if isinstance(embeddings_list, list): | ||
| for i, embedding in enumerate(embeddings_list): | ||
| yield StreamedEmbedding( | ||
| index=global_offset + i, | ||
| embedding=embedding, | ||
| embedding_type=type_name, | ||
| text=batch_texts[i] if i < len(batch_texts) else None, | ||
| ) | ||
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,120 @@ | ||
| """Tests for memory-efficient embed_stream functionality. | ||
|
|
||
| All embed_stream code lives in manually maintained files (.fernignore protected): | ||
| - src/cohere/client.py — Client.embed_stream() | ||
| - src/cohere/manually_maintained/streaming_embed.py — StreamedEmbedding, extraction helpers | ||
| """ | ||
|
|
||
| import unittest | ||
|
|
||
| from cohere.manually_maintained.streaming_embed import ( | ||
| StreamedEmbedding, | ||
| extract_embeddings_from_response, | ||
| ) | ||
| from cohere.config import embed_stream_batch_size | ||
|
|
||
|
|
||
| class TestStreamedEmbedding(unittest.TestCase): | ||
| """Test the StreamedEmbedding dataclass.""" | ||
|
|
||
| def test_creation(self): | ||
| emb = StreamedEmbedding(index=0, embedding=[0.1, 0.2], embedding_type="float", text="hello") | ||
| self.assertEqual(emb.index, 0) | ||
| self.assertEqual(emb.embedding, [0.1, 0.2]) | ||
| self.assertEqual(emb.embedding_type, "float") | ||
| self.assertEqual(emb.text, "hello") | ||
|
|
||
| def test_text_optional(self): | ||
| emb = StreamedEmbedding(index=0, embedding=[0.1], embedding_type="float") | ||
| self.assertIsNone(emb.text) | ||
|
|
||
|
|
||
| class TestExtractEmbeddings(unittest.TestCase): | ||
| """Test extract_embeddings_from_response for V1 and V2 formats.""" | ||
|
|
||
| def test_v1_embeddings_floats(self): | ||
| """V1 embeddings_floats response returns flat float embeddings.""" | ||
| response = { | ||
| "response_type": "embeddings_floats", | ||
| "embeddings": [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]], | ||
| } | ||
| results = list(extract_embeddings_from_response(response, ["hello", "world"])) | ||
|
|
||
| self.assertEqual(len(results), 2) | ||
| self.assertEqual(results[0].index, 0) | ||
| self.assertEqual(results[0].embedding, [0.1, 0.2, 0.3]) | ||
| self.assertEqual(results[0].embedding_type, "float") | ||
| self.assertEqual(results[0].text, "hello") | ||
| self.assertEqual(results[1].index, 1) | ||
| self.assertEqual(results[1].text, "world") | ||
|
|
||
| def test_v1_embeddings_by_type(self): | ||
| """V1 embeddings_by_type response returns typed embeddings.""" | ||
| response = { | ||
| "response_type": "embeddings_by_type", | ||
| "embeddings": { | ||
| "float_": [[0.1, 0.2], [0.3, 0.4]], | ||
| "int8": [[1, 2], [3, 4]], | ||
| }, | ||
| } | ||
| results = list(extract_embeddings_from_response(response, ["a", "b"])) | ||
|
|
||
| # 2 texts * 2 types = 4 embeddings | ||
| self.assertEqual(len(results), 4) | ||
| float_results = [r for r in results if r.embedding_type == "float"] | ||
| int8_results = [r for r in results if r.embedding_type == "int8"] | ||
| self.assertEqual(len(float_results), 2) | ||
| self.assertEqual(len(int8_results), 2) | ||
|
|
||
| def test_v2_response_format(self): | ||
| """V2 response (no response_type) returns dict embeddings.""" | ||
| response = { | ||
| "embeddings": { | ||
| "float_": [[0.1, 0.2], [0.3, 0.4]], | ||
| }, | ||
| } | ||
| results = list(extract_embeddings_from_response(response, ["x", "y"])) | ||
|
|
||
| self.assertEqual(len(results), 2) | ||
| self.assertEqual(results[0].embedding_type, "float") | ||
| self.assertEqual(results[0].text, "x") | ||
|
|
||
| def test_global_offset(self): | ||
| """Global offset adjusts indices for batched processing.""" | ||
| response = { | ||
| "response_type": "embeddings_floats", | ||
| "embeddings": [[0.1], [0.2]], | ||
| } | ||
| results = list(extract_embeddings_from_response(response, ["c", "d"], global_offset=100)) | ||
|
|
||
| self.assertEqual(results[0].index, 100) | ||
| self.assertEqual(results[1].index, 101) | ||
|
|
||
| def test_empty_embeddings(self): | ||
| """Empty response yields nothing.""" | ||
| response = {"response_type": "embeddings_floats", "embeddings": []} | ||
| results = list(extract_embeddings_from_response(response, [])) | ||
| self.assertEqual(results, []) | ||
|
|
||
| def test_texts_shorter_than_embeddings(self): | ||
| """Text is None when batch_texts runs out.""" | ||
| response = { | ||
| "response_type": "embeddings_floats", | ||
| "embeddings": [[0.1], [0.2], [0.3]], | ||
| } | ||
| results = list(extract_embeddings_from_response(response, ["only_one"])) | ||
|
|
||
| self.assertEqual(results[0].text, "only_one") | ||
| self.assertIsNone(results[1].text) | ||
| self.assertIsNone(results[2].text) | ||
|
|
||
|
|
||
| class TestBatchSizeConstant(unittest.TestCase): | ||
| """Test that batch_size defaults come from config, not magic numbers.""" | ||
|
|
||
| def test_default_batch_size_matches_api_limit(self): | ||
| self.assertEqual(embed_stream_batch_size, 96) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Duplicated extraction logic between response type branches
Low Severity
The
elsebranch (V2 format) at lines 61–74 is a near-exact copy of theembeddings_by_typebranch at lines 48–59, differing only by an extraisinstance(embeddings_obj, dict)guard. This duplication means any future bug fix or enhancement needs to be applied in both places. Additionally, sinceembed_streamonly calls the V1BaseCohere.embed()— which always returns a response withresponse_typeset to"embeddings_floats"or"embeddings_by_type"— theelsebranch is unreachable dead code in the current usage.Additional Locations (1)
src/cohere/manually_maintained/streaming_embed.py#L47-L59