AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

Perf: HuggingFaceEmbeddings Causes Excessive Device-To-Cpu Transfers Per Batch

HuggingFaceEmbeddings uses convert_to_numpy=True inside every micro-batch, causing repeated device-to-CPU synchronizations. Additionally, Chroma.from_texts re-embeds documents for each storage batch instead of embedding once. This leads to ~1.84x slowdown on MPS/CUDA for large corpora.

mediumConfidence 85%LangchainRetrieversVector Stores

Origin Analysis

Root cause 1: sentence_transformers.encode() defaults to convert_to_numpy=True, which calls .cpu().float().numpy() inside every micro-batch iteration, forcing a hardware command buffer flush and synchronization each time. Root cause 2: Chroma.from_texts creates batches without precomputed embeddings, then calls add_texts() for each storage batch, causing embed_documents() to recompute embeddings from scratch for every batch.
1. Initialize HuggingFaceEmbeddings with BAAI/bge-small-en-v1.5 and batch_size=32. 2. Embed 1,000 short texts on an MPS/CUDA device. 3. Profile the encode loop; observe 32 device-to-CPU transfers and synchronization points. 4. Benchmark: baseline ~1.157s vs direct sentence_transformers ~0.594s. 5. Use Chroma.from_texts on a corpus spanning multiple ChromaDB batches (>5,461 docs) and observe re-embedding per batch.

Fixing Code Block

def _embed(self, texts: list[str]) -> list[list[float]]: """Embed texts using the model on-device, moving to CPU once.""" encode_kwargs = dict(self.encode_kwargs) encode_kwargs["convert_to_tensor"] = True encode_kwargs.pop("convert_to_numpy", None) embeddings = self.client.encode( texts, batch_size=encode_kwargs.get("batch_size", 32), show_progress_bar=encode_kwargs.get("show_progress_bar", False), **encode_kwargs, ) if hasattr(embeddings, "cpu"): embeddings = embeddings.cpu().numpy() return embeddings.tolist() @classmethod def from_texts( cls, texts: List[str], embedding: Optional[Embeddings] = None, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, persist_directory: Optional[str] = None, client_settings: Optional[chromadb.config.Settings] = None, client: Optional[chromadb.Client] = None, collection_metadata: Optional[Dict] = None, **kwargs: Any, ) -> Chroma: chroma_collection = cls( collection_name=collection_name, persist_directory=persist_directory, client_settings=client_settings, client=client, collection_metadata=collection_metadata, embedding_function=embedding, **kwargs, ) if ids is None: ids = [str(uuid.uuid1()) for _ in texts] if metadatas is None: metadatas = [{} for _ in texts] if embedding is not None: embeddings = embedding.embed_documents(texts) else: embeddings = None batches = create_batches( api=chroma_collection, metadatas=metadatas, documents=texts, ids=ids, embeddings=embeddings, ) for batch in batches: chroma_collection.add_texts( texts=batch[0], metadatas=batch[1], ids=batch[3], embeddings=batch[2] if embeddings is not None else None, ) return chroma_collection
In _embed, we force convert_to_tensor=True and remove any conflicting convert_to_numpy from encode_kwargs, so sentence_transformers keeps all micro-batch outputs on device and performs a single .cpu().numpy() at the end. In Chroma.from_texts, we pre-compute all embeddings once using embedding.embed_documents(texts), then pass those embeddings through create_batches and into add_texts, avoiding re-embedding for each ChromaDB storage batch.

Edge Case Audit

On CPU-only machines, convert_to_tensor=True may slightly increase overhead due to tensor conversion; ensure sentence-transformers version supports convert_to_tensor (>=2.7.0 recommended). Pre-embedding the entire corpus before batching increases peak memory; for very large datasets, consider streaming. Multi-threaded or concurrent embedding calls may not be thread-safe with a shared SentenceTransformer client. Rollback: remove convert_to_tensor=True from _embed and revert from_texts to not precompute embeddings.

Ecosystem Topology

Agent Frameworks

LangChain, LlamaIndex, and Pydantic

  1. highProperty graph relation keys collide when entity IDs or labels contain underscores
  2. highCodeActAgent drops assistant tool-call metadata during handoff, leaving an orphan tool response
  3. high[Bug]: HierarchicalNodeParser async methods return the documents unsplit
  4. highLLM.predict_and_call fails with ValidationError for non-function-calling models when react_chat_formatter is omitted
  5. highAnthropic streaming server-tool input_json_delta overwrites completed client tool_use arguments due to stale cur_tool_call state