-
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
base: main
Are you sure you want to change the base?
Changes from all commits
4710b8a
80a9acb
101d3db
06a9eb0
f29d889
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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) |
| 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, | ||
| ) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Duplicated extraction logic between response type branchesLow Severity The Additional Locations (1) |
||
| 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() |


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.
Generator defers batch_size validation until iteration time
Medium Severity
Because
embed_streamcontainsyield from(making it a generator function), all code in its body — includingif batch_size < 1: raise ValueError(...)— is deferred until the generator is first iterated, not whenembed_stream()is called. A user callinggen = client.embed_stream(texts=["hi"], batch_size=0)gets no error; theValueErroronly surfaces later whengenis consumed. This contradicts the intent of providing eager input validation and can make debugging harder when the generator is passed around before being iterated.Reviewed by Cursor Bugbot for commit f29d889. Configure here.