From b8ef43cf5891b7024299a92a3bb3c98a3d1b8fd5 Mon Sep 17 00:00:00 2001 From: anush008 Date: Mon, 30 Nov 2026 18:27:19 +0530 Subject: [PATCH 01/12] perf: run text embeddings on the Apple GPU with CoreML --- README.md | 19 +++ fastembed/common/coreml.py | 131 ++++++++++++++++++ fastembed/common/model_description.py | 7 + fastembed/text/builtin_sentence_embedding.py | 2 +- fastembed/text/clip_embedding.py | 3 +- fastembed/text/onnx_embedding.py | 111 ++++++++++++++- fastembed/text/pooled_embedding.py | 10 +- fastembed/text/pooled_normalized_embedding.py | 12 +- fastembed/text/siglip_embedding.py | 3 +- fastembed/text/text_embedding.py | 6 + fastembed/text/text_embedding_base.py | 5 +- 11 files changed, 302 insertions(+), 7 deletions(-) create mode 100644 fastembed/common/coreml.py diff --git a/README.md b/README.md index dd6e24b8d..c811f95d6 100644 --- a/README.md +++ b/README.md @@ -229,6 +229,25 @@ print("The model BAAI/bge-small-en-v1.5 is ready to use on a GPU.") ``` +### On Apple Silicon + +FastEmbed supports running on Apple Silicon GPUs for accelerated inference. + +No extra installation is needed. + +```python +from fastembed import TextEmbedding + +embedding_model = TextEmbedding( + model_name="BAAI/bge-small-en-v1.5", + providers=["CoreMLExecutionProvider"] +) +embedding_model.warmup() +print("The model BAAI/bge-small-en-v1.5 is ready to use on Apple Silicon.") +``` + +The model is compiled for the GPU on first use, which can take a few minutes for larger models. `warmup()` does it upfront. + ## Usage with Qdrant Installation with Qdrant Client in Python: diff --git a/fastembed/common/coreml.py b/fastembed/common/coreml.py new file mode 100644 index 000000000..4c1ac2247 --- /dev/null +++ b/fastembed/common/coreml.py @@ -0,0 +1,131 @@ +from collections.abc import Sequence +from pathlib import Path +from typing import Any, cast + +import numpy as np +import onnxruntime as ort +from loguru import logger + +from fastembed.common.types import NumpyArray, OnnxProvider + +COREML_PROVIDER = "CoreMLExecutionProvider" +COREML_ROWS = 16 +COREML_LENGTHS = (64, 128, 256, 384, 512) +# smaller batches, e.g. single queries, are faster on the CPU than padded to 16 rows +COREML_MIN_ROWS = 4 +DEFAULT_COREML_OPTIONS = {"ModelFormat": "MLProgram", "MLComputeUnits": "CPUAndGPU"} + + +def requests_coreml(providers: Sequence[OnnxProvider] | None) -> bool: + if not providers: + return False + first = providers[0] + return (first if isinstance(first, str) else first[0]) == COREML_PROVIDER + + +def coreml_options(providers: Sequence[OnnxProvider]) -> dict[str, Any]: + first = providers[0] + return {**DEFAULT_COREML_OPTIONS, **({} if isinstance(first, str) else first[1])} + + +class CoreMLRunner: + def __init__( + self, + model_path: Path, + cache_dir: Path, + cpu_session: ort.InferenceSession, + options: dict[str, Any], + max_length: int | None = None, + lengths: Sequence[int] | None = None, + ): + sizes = sorted(set(lengths or COREML_LENGTHS)) + if not all(isinstance(size, int) and size > 0 for size in sizes): + raise ValueError(f"CoreML lengths must be positive ints, got {lengths!r}") + if max_length is not None and sizes[-1] > max_length: + # padding past the model's position embeddings fails, e.g. 77 tokens for CLIP + sizes = [size for size in sizes if size < max_length] + [max_length] + self.lengths = tuple(sizes) + self.model_path = str(model_path) + self.cache_dir = Path(cache_dir) + self.cpu_session = cpu_session + self.options = options + self.inputs = cpu_session.get_inputs() + self.sessions: dict[int, ort.InferenceSession] = {} + + def _create_session(self, length: int) -> ort.InferenceSession: + batch_dim, length_dim = self.inputs[0].shape[:2] + session_options = ort.SessionOptions() + session_options.add_free_dimension_override_by_name(batch_dim, COREML_ROWS) + session_options.add_free_dimension_override_by_name(length_dim, length) + # onnxruntime keys the cache by the model file, not by the overridden shape + cache = self.cache_dir / f"{COREML_ROWS}x{length}" + if not cache.exists(): + logger.info(f"Compiling {self.model_path} for CoreML at {length} tokens into {cache}") + options = {**self.options, "ModelCacheDirectory": str(cache)} + return ort.InferenceSession( + self.model_path, + sess_options=session_options, + providers=[(COREML_PROVIDER, options), "CPUExecutionProvider"], + ) + + def session(self, length: int) -> ort.InferenceSession: + if length not in self.sessions: + self.sessions[length] = self._create_session(length) + return self.sessions[length] + + def warmup(self, lengths: Sequence[int] | None = None) -> None: + """Compiles `lengths`, all by default, running one batch each: CoreML finishes + compiling for the device on the first run.""" + for length in lengths or self.lengths: + if length not in self.lengths: + raise ValueError(f"{length} is not one of the CoreML lengths {self.lengths}") + feed = { + model_input.name: np.full( + (COREML_ROWS, length), + int(model_input.name == "attention_mask"), + dtype=np.int32 if "int32" in model_input.type else np.int64, + ) + for model_input in self.inputs + } + self.session(length).run(None, feed) + + def run( + self, onnx_input: dict[str, NumpyArray], output_names: list[str] | None = None + ) -> list[NumpyArray]: + rows, width = onnx_input["input_ids"].shape + # without a mask the model attends to padding, so only rows can be padded + unmasked = "attention_mask" not in onnx_input + if rows < COREML_MIN_ROWS or (unmasked and width not in self.lengths): + return self.cpu_session.run(output_names, onnx_input) + chunks = [ + self._run_chunk( + {name: value[start : start + COREML_ROWS] for name, value in onnx_input.items()}, + output_names, + ) + for start in range(0, rows, COREML_ROWS) + ] + return [cast(NumpyArray, np.concatenate(outputs)) for outputs in zip(*chunks)] + + def _run_chunk( + self, chunk: dict[str, NumpyArray], output_names: list[str] | None + ) -> list[NumpyArray]: + rows, width = chunk["input_ids"].shape + mask = chunk.get("attention_mask") + used = width if mask is None else int(mask.any(axis=0).nonzero()[0].max(initial=0)) + 1 + length = next((size for size in self.lengths if size >= used), None) + if length is None: + return self.cpu_session.run(output_names, chunk) + + feed = { + name: np.pad(value[:, :used], ((0, COREML_ROWS - rows), (0, length - used))) + for name, value in chunk.items() + } + outputs = [] + for output in self.session(length).run(output_names, feed): + output = output[:rows] + if output.ndim >= 3 and output.shape[1] == length: # per token + restored = np.zeros((rows, width, *output.shape[2:]), dtype=output.dtype) + restored[:, :used] = output[:, :used] + output = restored + outputs.append(output) + return outputs diff --git a/fastembed/common/model_description.py b/fastembed/common/model_description.py index 0c539fd84..4f439d95c 100644 --- a/fastembed/common/model_description.py +++ b/fastembed/common/model_description.py @@ -20,6 +20,12 @@ def __post_init__(self) -> None: ) +@dataclass(frozen=True) +class CoreMLModel: + sources: ModelSource | None = None + model_file: str | None = None + + @dataclass(frozen=True) class BaseModelDescription: model: str @@ -35,6 +41,7 @@ class BaseModelDescription: class DenseModelDescription(BaseModelDescription): dim: int | None = None tasks: dict[str, Any] | None = field(default_factory=dict) + coreml: CoreMLModel | None = None def __post_init__(self) -> None: assert self.dim is not None, "dim is required for dense model description" diff --git a/fastembed/text/builtin_sentence_embedding.py b/fastembed/text/builtin_sentence_embedding.py index 45daf90d2..ee287ee7c 100644 --- a/fastembed/text/builtin_sentence_embedding.py +++ b/fastembed/text/builtin_sentence_embedding.py @@ -66,7 +66,7 @@ def _post_process_onnx_output( def _run_model( self, onnx_input: dict[str, Any], onnx_output_names: list[str] | None = None ) -> NumpyArray: - return self.model.run(onnx_output_names, onnx_input)[1] # type: ignore[union-attr] + return self._run_session(onnx_input, onnx_output_names)[1] class BuiltinSentenceEmbeddingWorker(OnnxTextEmbeddingWorker): diff --git a/fastembed/text/clip_embedding.py b/fastembed/text/clip_embedding.py index b918e9f26..f7db25d04 100644 --- a/fastembed/text/clip_embedding.py +++ b/fastembed/text/clip_embedding.py @@ -3,7 +3,7 @@ from fastembed.common.types import NumpyArray from fastembed.common.onnx_model import OnnxOutputContext from fastembed.text.onnx_embedding import OnnxTextEmbedding, OnnxTextEmbeddingWorker -from fastembed.common.model_description import DenseModelDescription, ModelSource +from fastembed.common.model_description import CoreMLModel, DenseModelDescription, ModelSource supported_clip_models: list[DenseModelDescription] = [ DenseModelDescription( @@ -17,6 +17,7 @@ size_in_GB=0.25, sources=ModelSource(hf="Qdrant/clip-ViT-B-32-text"), model_file="model.onnx", + coreml=CoreMLModel(), ), ] diff --git a/fastembed/text/onnx_embedding.py b/fastembed/text/onnx_embedding.py index 35b348635..bb6a45d5f 100644 --- a/fastembed/text/onnx_embedding.py +++ b/fastembed/text/onnx_embedding.py @@ -1,6 +1,11 @@ +import warnings +from dataclasses import replace +from pathlib import Path from typing import Any, Iterable, Sequence, Type -from fastembed.common.model_description import DenseModelDescription, ModelSource +from fastembed.common.coreml import CoreMLRunner, coreml_options, requests_coreml +from fastembed.common.model_description import CoreMLModel, DenseModelDescription, ModelSource +from fastembed.common.onnx_external_data import link_external_data from fastembed.common.onnx_model import OnnxOutputContext from fastembed.common.types import Device, NumpyArray, OnnxProvider from fastembed.common.utils import define_cache_dir, normalize @@ -22,6 +27,9 @@ _deprecated_tar_struct=True, ), model_file="model_optimized.onnx", + coreml=CoreMLModel( + sources=ModelSource(hf="BAAI/bge-base-en"), model_file="onnx/model.onnx" + ), ), DenseModelDescription( model="BAAI/bge-base-en-v1.5", @@ -37,6 +45,9 @@ _deprecated_tar_struct=True, ), model_file="model_optimized.onnx", + coreml=CoreMLModel( + sources=ModelSource(hf="BAAI/bge-base-en-v1.5"), model_file="onnx/model.onnx" + ), ), DenseModelDescription( model="BAAI/bge-large-en-v1.5", @@ -49,6 +60,7 @@ size_in_GB=1.20, sources=ModelSource(hf="Qdrant/bge-large-en-v1.5-onnx"), model_file="model.onnx", + coreml=CoreMLModel(), ), DenseModelDescription( model="BAAI/bge-small-en", @@ -64,6 +76,9 @@ _deprecated_tar_struct=True, ), model_file="model_optimized.onnx", + coreml=CoreMLModel( + sources=ModelSource(hf="Xenova/bge-small-en"), model_file="onnx/model.onnx" + ), ), DenseModelDescription( model="BAAI/bge-small-en-v1.5", @@ -76,6 +91,9 @@ size_in_GB=0.067, sources=ModelSource(hf="Qdrant/bge-small-en-v1.5-onnx-Q"), model_file="model_optimized.onnx", + coreml=CoreMLModel( + sources=ModelSource(hf="BAAI/bge-small-en-v1.5"), model_file="onnx/model.onnx" + ), ), DenseModelDescription( model="BAAI/bge-small-zh-v1.5", @@ -91,6 +109,9 @@ _deprecated_tar_struct=True, ), model_file="model_optimized.onnx", + coreml=CoreMLModel( + sources=ModelSource(hf="Xenova/bge-small-zh-v1.5"), model_file="onnx/model.onnx" + ), ), DenseModelDescription( model="mixedbread-ai/mxbai-embed-large-v1", @@ -103,6 +124,7 @@ size_in_GB=0.64, sources=ModelSource(hf="mixedbread-ai/mxbai-embed-large-v1"), model_file="onnx/model.onnx", + coreml=CoreMLModel(), ), DenseModelDescription( model="snowflake/snowflake-arctic-embed-xs", @@ -115,6 +137,7 @@ size_in_GB=0.09, sources=ModelSource(hf="Snowflake/snowflake-arctic-embed-xs"), model_file="onnx/model.onnx", + coreml=CoreMLModel(), ), DenseModelDescription( model="snowflake/snowflake-arctic-embed-s", @@ -127,6 +150,7 @@ size_in_GB=0.13, sources=ModelSource(hf="Snowflake/snowflake-arctic-embed-s"), model_file="onnx/model.onnx", + coreml=CoreMLModel(), ), DenseModelDescription( model="snowflake/snowflake-arctic-embed-m", @@ -139,6 +163,7 @@ size_in_GB=0.43, sources=ModelSource(hf="Snowflake/snowflake-arctic-embed-m"), model_file="onnx/model.onnx", + coreml=CoreMLModel(), ), DenseModelDescription( model="snowflake/snowflake-arctic-embed-m-long", @@ -163,6 +188,7 @@ size_in_GB=1.02, sources=ModelSource(hf="Snowflake/snowflake-arctic-embed-l"), model_file="onnx/model.onnx", + coreml=CoreMLModel(), ), DenseModelDescription( model="jinaai/jina-clip-v1", @@ -195,6 +221,10 @@ class OnnxTextEmbedding(TextEmbeddingBase, OnnxTextModel[NumpyArray]): """Implementation of the Flag Embedding model.""" + _coreml_dir: Path | None = None + _coreml_runner: CoreMLRunner | None = None + _coreml_lengths: Sequence[int] | None = None + @classmethod def _list_supported_models(cls) -> list[DenseModelDescription]: """ @@ -245,6 +275,7 @@ def __init__( self.lazy_load = lazy_load self._extra_session_options = self._select_exposed_session_options(kwargs) self._max_batch_tokens = self._select_max_batch_tokens(kwargs) + self._coreml_lengths = kwargs.get("coreml_lengths") # List of device ids, that can be used for data parallel processing in workers self.device_ids = device_ids self.cuda = cuda @@ -265,10 +296,33 @@ def __init__( local_files_only=self._local_files_only, specific_model_path=self._specific_model_path, ) + self._coreml_dir = self._download_coreml_model() if not self.lazy_load: self.load_onnx_model() + def _download_coreml_model(self) -> Path | None: + if not requests_coreml(self.providers) or self._specific_model_path: + return None + coreml = self.model_description.coreml + if coreml is None: + warnings.warn( + f"{self.model_name} has no CoreML support, CoreML may run it slower than the CPU", + stacklevel=3, + ) + return None + if coreml.sources is None: + return self._model_dir + export = replace( + self.model_description, + sources=coreml.sources, + model_file=coreml.model_file or self.model_description.model_file, + additional_files=[], + ) + return self.download_model( + export, str(self.cache_dir), local_files_only=self._local_files_only + ) + def embed( self, documents: str | Iterable[str], @@ -331,7 +385,28 @@ def _post_process_onnx_output( raise ValueError(f"Unsupported embedding shape: {embeddings.shape}") return normalize(processed_embeddings) + def _batch_token_budget(self) -> int | None: + # CoreML pads batches to fixed shapes, smaller batches would only waste them + if self._coreml_dir is not None: + return None + return super()._batch_token_budget() + + def _run_session( + self, onnx_input: dict[str, Any], onnx_output_names: list[str] | None = None + ) -> list[NumpyArray]: + if self._coreml_runner is not None: + return self._coreml_runner.run(onnx_input, onnx_output_names) + return self.model.run(onnx_output_names, onnx_input) # type: ignore[union-attr] + + def _run_model( + self, onnx_input: dict[str, Any], onnx_output_names: list[str] | None = None + ) -> NumpyArray: + return self._run_session(onnx_input, onnx_output_names)[0] + def load_onnx_model(self) -> None: + if self._coreml_dir is not None: + self._load_coreml_model(self._coreml_dir) + return self._load_onnx_model( model_dir=self._model_dir, model_file=self.model_description.model_file, @@ -343,6 +418,40 @@ def load_onnx_model(self) -> None: additional_files=self.model_description.additional_files, ) + def _load_coreml_model(self, model_dir: Path) -> None: + coreml = self.model_description.coreml + assert coreml is not None + model_file = coreml.model_file or self.model_description.model_file + additional_files = [] if coreml.sources else self.model_description.additional_files + # the CPU session runs the batches too small for CoreML + self._load_onnx_model( + model_dir=model_dir, + model_file=model_file, + threads=self.threads, + providers=["CPUExecutionProvider"], + extra_session_options=self._extra_session_options, + additional_files=additional_files, + ) + try: + model_path = link_external_data(model_dir, model_file, additional_files) + except OSError: + model_path = model_dir / model_file + assert self.model is not None and self.tokenizer is not None and self.cache_dir + self._coreml_runner = CoreMLRunner( + model_path=model_path, + cache_dir=Path(self.cache_dir) / "coreml" / self.model_name.replace("/", "--"), + cpu_session=self.model, + options=coreml_options(self.providers), # type: ignore[arg-type] + max_length=(self.tokenizer.truncation or {}).get("max_length"), + lengths=self._coreml_lengths, + ) + + def warmup(self, lengths: Sequence[int] | None = None) -> None: + if self.model is None: + self.load_onnx_model() + if self._coreml_runner is not None: + self._coreml_runner.warmup(lengths) + def token_count( self, texts: str | Iterable[str], batch_size: int = 1024, **kwargs: Any ) -> int: diff --git a/fastembed/text/pooled_embedding.py b/fastembed/text/pooled_embedding.py index 3dac58256..20f223a63 100644 --- a/fastembed/text/pooled_embedding.py +++ b/fastembed/text/pooled_embedding.py @@ -7,7 +7,7 @@ from fastembed.common.onnx_model import OnnxOutputContext from fastembed.common.utils import mean_pooling from fastembed.text.onnx_embedding import OnnxTextEmbedding, OnnxTextEmbeddingWorker -from fastembed.common.model_description import DenseModelDescription, ModelSource +from fastembed.common.model_description import CoreMLModel, DenseModelDescription, ModelSource supported_pooled_models: list[DenseModelDescription] = [ DenseModelDescription( @@ -21,6 +21,7 @@ size_in_GB=0.52, sources=ModelSource(hf="nomic-ai/nomic-embed-text-v1.5"), model_file="onnx/model.onnx", + coreml=CoreMLModel(), ), DenseModelDescription( model="nomic-ai/nomic-embed-text-v1.5-Q", @@ -45,6 +46,7 @@ size_in_GB=0.52, sources=ModelSource(hf="nomic-ai/nomic-embed-text-v1"), model_file="onnx/model.onnx", + coreml=CoreMLModel(), ), DenseModelDescription( model="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2", @@ -57,6 +59,10 @@ size_in_GB=0.22, sources=ModelSource(hf="Qdrant/paraphrase-multilingual-MiniLM-L12-v2-onnx-Q"), model_file="model_optimized.onnx", + coreml=CoreMLModel( + sources=ModelSource(hf="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"), + model_file="onnx/model.onnx", + ), ), DenseModelDescription( model="sentence-transformers/paraphrase-multilingual-mpnet-base-v2", @@ -69,6 +75,7 @@ size_in_GB=1.00, sources=ModelSource(hf="Xenova/paraphrase-multilingual-mpnet-base-v2"), model_file="onnx/model.onnx", + coreml=CoreMLModel(), ), DenseModelDescription( model="intfloat/multilingual-e5-large", @@ -84,6 +91,7 @@ _deprecated_tar_struct=True, ), model_file="model.onnx", + coreml=CoreMLModel(), additional_files=["model.onnx_data"], ), ] diff --git a/fastembed/text/pooled_normalized_embedding.py b/fastembed/text/pooled_normalized_embedding.py index f74728578..84d0a9b29 100644 --- a/fastembed/text/pooled_normalized_embedding.py +++ b/fastembed/text/pooled_normalized_embedding.py @@ -6,7 +6,7 @@ from fastembed.common.utils import normalize from fastembed.text.onnx_embedding import OnnxTextEmbedding, OnnxTextEmbeddingWorker from fastembed.text.pooled_embedding import PooledEmbedding -from fastembed.common.model_description import DenseModelDescription, ModelSource +from fastembed.common.model_description import CoreMLModel, DenseModelDescription, ModelSource supported_pooled_normalized_models: list[DenseModelDescription] = [ DenseModelDescription( @@ -23,6 +23,7 @@ _deprecated_tar_struct=True, ), model_file="model.onnx", + coreml=CoreMLModel(), ), DenseModelDescription( model="jinaai/jina-embeddings-v2-base-en", @@ -35,6 +36,7 @@ size_in_GB=0.52, sources=ModelSource(hf="Xenova/jina-embeddings-v2-base-en"), model_file="onnx/model.onnx", + coreml=CoreMLModel(), ), DenseModelDescription( model="jinaai/jina-embeddings-v2-small-en", @@ -47,6 +49,7 @@ size_in_GB=0.12, sources=ModelSource(hf="Xenova/jina-embeddings-v2-small-en"), model_file="onnx/model.onnx", + coreml=CoreMLModel(), ), DenseModelDescription( model="jinaai/jina-embeddings-v2-base-de", @@ -59,6 +62,7 @@ size_in_GB=0.64, sources=ModelSource(hf="jinaai/jina-embeddings-v2-base-de"), model_file="onnx/model.onnx", + coreml=CoreMLModel(), ), DenseModelDescription( model="jinaai/jina-embeddings-v2-base-code", @@ -71,6 +75,7 @@ size_in_GB=0.64, sources=ModelSource(hf="jinaai/jina-embeddings-v2-base-code"), model_file="onnx/model.onnx", + coreml=CoreMLModel(), ), DenseModelDescription( model="jinaai/jina-embeddings-v2-base-zh", @@ -83,6 +88,7 @@ size_in_GB=0.64, sources=ModelSource(hf="jinaai/jina-embeddings-v2-base-zh"), model_file="onnx/model.onnx", + coreml=CoreMLModel(), ), DenseModelDescription( model="jinaai/jina-embeddings-v2-base-es", @@ -95,6 +101,7 @@ size_in_GB=0.64, sources=ModelSource(hf="jinaai/jina-embeddings-v2-base-es"), model_file="onnx/model.onnx", + coreml=CoreMLModel(), ), DenseModelDescription( model="thenlper/gte-base", @@ -107,6 +114,7 @@ size_in_GB=0.44, sources=ModelSource(hf="thenlper/gte-base"), model_file="onnx/model.onnx", + coreml=CoreMLModel(), ), DenseModelDescription( model="thenlper/gte-large", @@ -119,6 +127,7 @@ size_in_GB=1.20, sources=ModelSource(hf="Qdrant/gte-large-onnx"), model_file="model.onnx", + coreml=CoreMLModel(), ), DenseModelDescription( model="Qdrant/constella-nano", @@ -132,6 +141,7 @@ size_in_GB=0.14, sources=ModelSource(hf="Qdrant/constella-nano"), model_file="model.onnx", + coreml=CoreMLModel(), ), ] diff --git a/fastembed/text/siglip_embedding.py b/fastembed/text/siglip_embedding.py index f1659c1df..76815b811 100644 --- a/fastembed/text/siglip_embedding.py +++ b/fastembed/text/siglip_embedding.py @@ -1,7 +1,7 @@ from pathlib import Path from typing import Any, Type -from fastembed.common.model_description import DenseModelDescription, ModelSource +from fastembed.common.model_description import CoreMLModel, DenseModelDescription, ModelSource from fastembed.text.onnx_embedding import OnnxTextEmbedding, OnnxTextEmbeddingWorker supported_siglip_models: list[DenseModelDescription] = [ @@ -16,6 +16,7 @@ size_in_GB=1.13, sources=ModelSource(hf="onnx-community/siglip2-base-patch16-224-ONNX"), model_file="onnx/text_model.onnx", + coreml=CoreMLModel(), ), ] diff --git a/fastembed/text/text_embedding.py b/fastembed/text/text_embedding.py index f65bfb3ba..e35c4919d 100644 --- a/fastembed/text/text_embedding.py +++ b/fastembed/text/text_embedding.py @@ -125,6 +125,8 @@ def __init__( 2048, 0 turns the limit off. mmap (bool): For static models (minishlab potion), whether to memory-map the embedding matrix instead of reading it into memory. Defaults to False. + coreml_lengths (Sequence[int]): For CoreML, the token lengths to compile. + Longer texts run on the CPU. Defaults to (64, 128, 256, 384, 512). """ super().__init__(model_name, cache_dir, threads, **kwargs) if model_name.lower() == "jinaai/jina-embeddings-v2-base-de": @@ -238,6 +240,10 @@ def passage_embed(self, texts: Iterable[str], **kwargs: Any) -> Iterable[NumpyAr # This is model-specific, so that different models can have specialized implementations yield from self.model.passage_embed(texts, **kwargs) + def warmup(self, lengths: Sequence[int] | None = None) -> None: + """Loads the model and, for CoreML, compiles `lengths` (all by default) up front.""" + self.model.warmup(lengths) + def token_count( self, texts: str | Iterable[str], batch_size: int = 1024, **kwargs: Any ) -> int: diff --git a/fastembed/text/text_embedding_base.py b/fastembed/text/text_embedding_base.py index 13bc4f732..e58831c4e 100644 --- a/fastembed/text/text_embedding_base.py +++ b/fastembed/text/text_embedding_base.py @@ -1,4 +1,4 @@ -from typing import Iterable, Any +from typing import Iterable, Any, Sequence from fastembed.common.model_description import DenseModelDescription from fastembed.common.types import NumpyArray @@ -73,3 +73,6 @@ def embedding_size(self) -> int: def token_count(self, texts: str | Iterable[str], **kwargs: Any) -> int: """Returns the number of tokens in the texts.""" raise NotImplementedError("Subclasses must implement this method") + + def warmup(self, lengths: Sequence[int] | None = None) -> None: + """Prepares the model for its first batch, nothing to do by default.""" From 69da09ac83fd15de3cb414be605516340f6c47ea Mon Sep 17 00:00:00 2001 From: anush008 Date: Mon, 30 Nov 2026 18:54:49 +0530 Subject: [PATCH 02/12] fix: use np.flatnonzero so mypy passes with numpy 2.4 stubs --- fastembed/common/coreml.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fastembed/common/coreml.py b/fastembed/common/coreml.py index 4c1ac2247..df3c7b7f2 100644 --- a/fastembed/common/coreml.py +++ b/fastembed/common/coreml.py @@ -111,7 +111,7 @@ def _run_chunk( ) -> list[NumpyArray]: rows, width = chunk["input_ids"].shape mask = chunk.get("attention_mask") - used = width if mask is None else int(mask.any(axis=0).nonzero()[0].max(initial=0)) + 1 + used = width if mask is None else int(np.flatnonzero(mask.any(axis=0)).max(initial=0)) + 1 length = next((size for size in self.lengths if size >= used), None) if length is None: return self.cpu_session.run(output_names, chunk) From 8cf9439748437bfa8d6d578f67bd0c9b5cc2443d Mon Sep 17 00:00:00 2001 From: anush008 Date: Mon, 30 Nov 2026 22:48:10 +0530 Subject: [PATCH 03/12] chore: Address review --- fastembed/common/coreml.py | 45 ++++++++++++++++++++------------ fastembed/text/onnx_embedding.py | 7 +++++ fastembed/text/text_embedding.py | 8 ++++-- 3 files changed, 42 insertions(+), 18 deletions(-) diff --git a/fastembed/common/coreml.py b/fastembed/common/coreml.py index df3c7b7f2..d611f47b4 100644 --- a/fastembed/common/coreml.py +++ b/fastembed/common/coreml.py @@ -1,4 +1,4 @@ -from collections.abc import Sequence +from collections.abc import Iterable, Sequence from pathlib import Path from typing import Any, cast @@ -37,6 +37,7 @@ def __init__( options: dict[str, Any], max_length: int | None = None, lengths: Sequence[int] | None = None, + cpu_max_tokens: int | None = None, ): sizes = sorted(set(lengths or COREML_LENGTHS)) if not all(isinstance(size, int) and size > 0 for size in sizes): @@ -48,6 +49,7 @@ def __init__( self.model_path = str(model_path) self.cache_dir = Path(cache_dir) self.cpu_session = cpu_session + self.cpu_max_tokens = cpu_max_tokens self.options = options self.inputs = cpu_session.get_inputs() self.sessions: dict[int, ort.InferenceSession] = {} @@ -92,19 +94,10 @@ def warmup(self, lengths: Sequence[int] | None = None) -> None: def run( self, onnx_input: dict[str, NumpyArray], output_names: list[str] | None = None ) -> list[NumpyArray]: - rows, width = onnx_input["input_ids"].shape - # without a mask the model attends to padding, so only rows can be padded - unmasked = "attention_mask" not in onnx_input - if rows < COREML_MIN_ROWS or (unmasked and width not in self.lengths): - return self.cpu_session.run(output_names, onnx_input) - chunks = [ - self._run_chunk( - {name: value[start : start + COREML_ROWS] for name, value in onnx_input.items()}, - output_names, - ) - for start in range(0, rows, COREML_ROWS) - ] - return [cast(NumpyArray, np.concatenate(outputs)) for outputs in zip(*chunks)] + return self._concat( + self._run_chunk(self._rows(onnx_input, start, COREML_ROWS), output_names) + for start in range(0, onnx_input["input_ids"].shape[0], COREML_ROWS) + ) def _run_chunk( self, chunk: dict[str, NumpyArray], output_names: list[str] | None @@ -113,8 +106,9 @@ def _run_chunk( mask = chunk.get("attention_mask") used = width if mask is None else int(np.flatnonzero(mask.any(axis=0)).max(initial=0)) + 1 length = next((size for size in self.lengths if size >= used), None) - if length is None: - return self.cpu_session.run(output_names, chunk) + # without a mask the model attends to padding, so only rows can be padded + if rows < COREML_MIN_ROWS or length is None or (mask is None and length != width): + return self._run_cpu(chunk, output_names) feed = { name: np.pad(value[:, :used], ((0, COREML_ROWS - rows), (0, length - used))) @@ -129,3 +123,22 @@ def _run_chunk( output = restored outputs.append(output) return outputs + + def _run_cpu( + self, chunk: dict[str, NumpyArray], output_names: list[str] | None + ) -> list[NumpyArray]: + rows, width = chunk["input_ids"].shape + # keep long texts within the CPU's token budget, as batching does without CoreML + step = rows if self.cpu_max_tokens is None else max(1, self.cpu_max_tokens // width) + return self._concat( + self.cpu_session.run(output_names, self._rows(chunk, start, step)) + for start in range(0, rows, step) + ) + + @staticmethod + def _rows(batch: dict[str, NumpyArray], start: int, count: int) -> dict[str, NumpyArray]: + return {name: value[start : start + count] for name, value in batch.items()} + + @staticmethod + def _concat(parts: Iterable[list[NumpyArray]]) -> list[NumpyArray]: + return [cast(NumpyArray, np.concatenate(outputs)) for outputs in zip(*parts)] diff --git a/fastembed/text/onnx_embedding.py b/fastembed/text/onnx_embedding.py index 65dc6a588..1ffa4cf60 100644 --- a/fastembed/text/onnx_embedding.py +++ b/fastembed/text/onnx_embedding.py @@ -392,6 +392,12 @@ def _batch_token_budget(self) -> int | None: return None return super()._batch_token_budget() + def _get_worker_init_kwargs(self) -> dict[str, Any]: + kwargs = super()._get_worker_init_kwargs() + if self._coreml_lengths is not None: + kwargs["coreml_lengths"] = self._coreml_lengths + return kwargs + def _run_session( self, onnx_input: dict[str, Any], onnx_output_names: list[str] | None = None ) -> list[NumpyArray]: @@ -445,6 +451,7 @@ def _load_coreml_model(self, model_dir: Path) -> None: options=coreml_options(self.providers), # type: ignore[arg-type] max_length=(self.tokenizer.truncation or {}).get("max_length"), lengths=self._coreml_lengths, + cpu_max_tokens=super()._batch_token_budget(), ) def warmup(self, lengths: Sequence[int] | None = None) -> None: diff --git a/fastembed/text/text_embedding.py b/fastembed/text/text_embedding.py index 52e191d34..367204dc2 100644 --- a/fastembed/text/text_embedding.py +++ b/fastembed/text/text_embedding.py @@ -127,7 +127,8 @@ def __init__( mmap (bool): For static models (minishlab potion), whether to memory-map the embedding matrix instead of reading it into memory. Defaults to False. coreml_lengths (Sequence[int]): For CoreML, the token lengths to compile. - Longer texts run on the CPU. Defaults to (64, 128, 256, 384, 512). + Longer texts run on the CPU. Lengths over the model's limit are replaced + by the limit, e.g. 77 for CLIP. Defaults to (64, 128, 256, 384, 512). """ super().__init__(model_name, cache_dir, threads, **kwargs) if model_name.lower() == "jinaai/jina-embeddings-v2-base-de": @@ -242,7 +243,10 @@ def passage_embed(self, texts: Iterable[str], **kwargs: Any) -> Iterable[NumpyAr yield from self.model.passage_embed(texts, **kwargs) def warmup(self, lengths: Sequence[int] | None = None) -> None: - """Loads the model and, for CoreML, compiles `lengths` (all by default) up front.""" + """Loads the model and, for CoreML, compiles `lengths` (all by default) up front. + + `lengths` must be among the model's CoreML lengths, after the model's limit applies. + """ self.model.warmup(lengths) def token_count( From 0978d6c13b4ee8a048d32ddd3863d9d1a0a46bb6 Mon Sep 17 00:00:00 2001 From: anush008 Date: Mon, 30 Nov 2026 23:48:24 +0530 Subject: [PATCH 04/12] chore: forward max_batch_tokens to CoreML workers --- fastembed/text/onnx_embedding.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/fastembed/text/onnx_embedding.py b/fastembed/text/onnx_embedding.py index 1ffa4cf60..e623e91a8 100644 --- a/fastembed/text/onnx_embedding.py +++ b/fastembed/text/onnx_embedding.py @@ -396,6 +396,8 @@ def _get_worker_init_kwargs(self) -> dict[str, Any]: kwargs = super()._get_worker_init_kwargs() if self._coreml_lengths is not None: kwargs["coreml_lengths"] = self._coreml_lengths + if self._max_batch_tokens is not None: + kwargs["max_batch_tokens"] = self._max_batch_tokens return kwargs def _run_session( From 68b21a082bd44266b1fa89724a743b84c1138cba Mon Sep 17 00:00:00 2001 From: anush008 Date: Tue, 1 Dec 2026 22:37:53 +0530 Subject: [PATCH 05/12] refactor: move CoreML support into CoreMLMixin --- fastembed/common/coreml.py | 139 +++++++++++++++++-- fastembed/text/builtin_sentence_embedding.py | 2 +- fastembed/text/onnx_embedding.py | 100 +------------ fastembed/text/onnx_text_model.py | 5 +- 4 files changed, 138 insertions(+), 108 deletions(-) diff --git a/fastembed/common/coreml.py b/fastembed/common/coreml.py index d611f47b4..065faafc1 100644 --- a/fastembed/common/coreml.py +++ b/fastembed/common/coreml.py @@ -1,4 +1,6 @@ -from collections.abc import Iterable, Sequence +import warnings +from collections.abc import Callable, Iterable, Sequence +from dataclasses import replace from pathlib import Path from typing import Any, cast @@ -6,6 +8,10 @@ import onnxruntime as ort from loguru import logger +from fastembed.common.model_description import DenseModelDescription +from fastembed.common.model_management import ModelManagement +from fastembed.common.onnx_external_data import link_external_data +from fastembed.common.onnx_model import OnnxModel from fastembed.common.types import NumpyArray, OnnxProvider COREML_PROVIDER = "CoreMLExecutionProvider" @@ -38,6 +44,8 @@ def __init__( max_length: int | None = None, lengths: Sequence[int] | None = None, cpu_max_tokens: int | None = None, + cpu_run: Callable[[list[str] | None, dict[str, NumpyArray]], list[NumpyArray]] + | None = None, ): sizes = sorted(set(lengths or COREML_LENGTHS)) if not all(isinstance(size, int) and size > 0 for size in sizes): @@ -48,27 +56,35 @@ def __init__( self.lengths = tuple(sizes) self.model_path = str(model_path) self.cache_dir = Path(cache_dir) - self.cpu_session = cpu_session + self.cpu_run = cpu_run or cpu_session.run self.cpu_max_tokens = cpu_max_tokens self.options = options self.inputs = cpu_session.get_inputs() self.sessions: dict[int, ort.InferenceSession] = {} def _create_session(self, length: int) -> ort.InferenceSession: + import fcntl # CoreML is macOS only, fcntl isn't on Windows + batch_dim, length_dim = self.inputs[0].shape[:2] session_options = ort.SessionOptions() session_options.add_free_dimension_override_by_name(batch_dim, COREML_ROWS) session_options.add_free_dimension_override_by_name(length_dim, length) # onnxruntime keys the cache by the model file, not by the overridden shape cache = self.cache_dir / f"{COREML_ROWS}x{length}" - if not cache.exists(): - logger.info(f"Compiling {self.model_path} for CoreML at {length} tokens into {cache}") options = {**self.options, "ModelCacheDirectory": str(cache)} - return ort.InferenceSession( - self.model_path, - sess_options=session_options, - providers=[(COREML_PROVIDER, options), "CPUExecutionProvider"], - ) + cache.parent.mkdir(parents=True, exist_ok=True) + # parallel workers compile one at a time, the others load the compiled model + with open(cache.with_suffix(".lock"), "w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + if not cache.exists(): + logger.info( + f"Compiling {self.model_path} for CoreML at {length} tokens into {cache}" + ) + return ort.InferenceSession( + self.model_path, + sess_options=session_options, + providers=[(COREML_PROVIDER, options), "CPUExecutionProvider"], + ) def session(self, length: int) -> ort.InferenceSession: if length not in self.sessions: @@ -131,7 +147,7 @@ def _run_cpu( # keep long texts within the CPU's token budget, as batching does without CoreML step = rows if self.cpu_max_tokens is None else max(1, self.cpu_max_tokens // width) return self._concat( - self.cpu_session.run(output_names, self._rows(chunk, start, step)) + self.cpu_run(output_names, self._rows(chunk, start, step)) for start in range(0, rows, step) ) @@ -142,3 +158,106 @@ def _rows(batch: dict[str, NumpyArray], start: int, count: int) -> dict[str, Num @staticmethod def _concat(parts: Iterable[list[NumpyArray]]) -> list[NumpyArray]: return [cast(NumpyArray, np.concatenate(outputs)) for outputs in zip(*parts)] + + +class CoreMLMixin(OnnxModel[NumpyArray], ModelManagement[DenseModelDescription]): + model_name: str + model_description: DenseModelDescription + providers: Sequence[OnnxProvider] | None + threads: int | None + cache_dir: str | None + _extra_session_options: dict[str, Any] + _local_files_only: bool + _specific_model_path: str | None + + _coreml_dir: Path | None = None + _coreml_runner: CoreMLRunner | None = None + _coreml_lengths: Sequence[int] | None = None + + def _init_coreml(self, lengths: Sequence[int] | None) -> None: + self._coreml_lengths = lengths + if not requests_coreml(self.providers) or self._specific_model_path: + return + if COREML_PROVIDER not in ort.get_available_providers(): + return # loading the model raises that the provider isn't available + coreml = self.model_description.coreml + if coreml is None: + warnings.warn( + f"{self.model_name} has no CoreML support, CoreML may run it slower than the CPU", + stacklevel=3, + ) + return + if coreml.sources is None: + self._coreml_dir = self._model_dir + return + export = replace( + self.model_description, + sources=coreml.sources, + model_file=coreml.model_file or self.model_description.model_file, + additional_files=[], + ) + self._coreml_dir = self.download_model( + export, str(self.cache_dir), local_files_only=self._local_files_only + ) + + def _load_coreml_model(self) -> None: + coreml = self.model_description.coreml + assert coreml is not None and self._coreml_dir is not None + model_file = coreml.model_file or self.model_description.model_file + additional_files = [] if coreml.sources else self.model_description.additional_files + # the CPU session runs the batches too small for CoreML + self._load_onnx_model( + model_dir=self._coreml_dir, + model_file=model_file, + threads=self.threads, + providers=["CPUExecutionProvider"], + extra_session_options=self._extra_session_options, + additional_files=additional_files, + ) + try: + model_path = link_external_data(self._coreml_dir, model_file, additional_files) + except OSError: + model_path = self._coreml_dir / model_file + assert self.model is not None and self.tokenizer is not None and self.cache_dir + options = coreml_options(self.providers) # type: ignore[arg-type] + cache_dir = Path( + options.pop("ModelCacheDirectory", None) or Path(self.cache_dir) / "coreml" + ) + self._coreml_runner = CoreMLRunner( + model_path=model_path, + cache_dir=cache_dir / self.model_name.replace("/", "--"), + cpu_session=self.model, + options=options, + max_length=(self.tokenizer.truncation or {}).get("max_length"), + lengths=self._coreml_lengths, + cpu_max_tokens=super()._batch_token_budget(), + # releases the CPU session's memory after each call, as without CoreML + cpu_run=super()._run_model_with_shrinkage, + ) + + def warmup(self, lengths: Sequence[int] | None = None) -> None: + if getattr(self, "model", None) is None: + self.load_onnx_model() + if self._coreml_runner is not None: + self._coreml_runner.warmup(lengths) + + def _run_model_with_shrinkage( + self, output_names: list[str] | None, onnx_input: dict[str, Any] + ) -> list[Any]: + if self._coreml_runner is not None: + return self._coreml_runner.run(onnx_input, output_names) + return super()._run_model_with_shrinkage(output_names, onnx_input) + + def _batch_token_budget(self) -> int | None: + # CoreML pads batches to fixed shapes, smaller batches would only waste them + if self._coreml_dir is not None and self._max_batch_tokens is None: + return None + return super()._batch_token_budget() + + def _get_worker_init_kwargs(self) -> dict[str, Any]: + kwargs = super()._get_worker_init_kwargs() + if self._coreml_lengths is not None: + kwargs["coreml_lengths"] = self._coreml_lengths + if self._max_batch_tokens is not None: + kwargs["max_batch_tokens"] = self._max_batch_tokens + return kwargs diff --git a/fastembed/text/builtin_sentence_embedding.py b/fastembed/text/builtin_sentence_embedding.py index 8b4fd79a8..cee00b533 100644 --- a/fastembed/text/builtin_sentence_embedding.py +++ b/fastembed/text/builtin_sentence_embedding.py @@ -65,7 +65,7 @@ def _post_process_onnx_output( def _run_model( self, onnx_input: dict[str, Any], onnx_output_names: list[str] | None = None ) -> NumpyArray: - return self._run_session(onnx_input, onnx_output_names)[1] + return self._run_model_with_shrinkage(onnx_output_names, onnx_input)[1] class BuiltinSentenceEmbeddingWorker(OnnxTextEmbeddingWorker): diff --git a/fastembed/text/onnx_embedding.py b/fastembed/text/onnx_embedding.py index e623e91a8..c7f43403d 100644 --- a/fastembed/text/onnx_embedding.py +++ b/fastembed/text/onnx_embedding.py @@ -1,12 +1,8 @@ -import warnings from collections.abc import Iterable, Sequence -from dataclasses import replace -from pathlib import Path from typing import Any -from fastembed.common.coreml import CoreMLRunner, coreml_options, requests_coreml +from fastembed.common.coreml import CoreMLMixin from fastembed.common.model_description import CoreMLModel, DenseModelDescription, ModelSource -from fastembed.common.onnx_external_data import link_external_data from fastembed.common.onnx_model import OnnxOutputContext from fastembed.common.types import Device, NumpyArray, OnnxProvider from fastembed.common.utils import define_cache_dir, first_token_pooling, normalize @@ -219,13 +215,9 @@ ] -class OnnxTextEmbedding(TextEmbeddingBase, OnnxTextModel[NumpyArray]): +class OnnxTextEmbedding(CoreMLMixin, TextEmbeddingBase, OnnxTextModel[NumpyArray]): """Implementation of the Flag Embedding model.""" - _coreml_dir: Path | None = None - _coreml_runner: CoreMLRunner | None = None - _coreml_lengths: Sequence[int] | None = None - @classmethod def _list_supported_models(cls) -> list[DenseModelDescription]: """ @@ -276,7 +268,6 @@ def __init__( self.lazy_load = lazy_load self._extra_session_options = self._select_exposed_session_options(kwargs) self._max_batch_tokens = self._select_max_batch_tokens(kwargs) - self._coreml_lengths = kwargs.get("coreml_lengths") # List of device ids, that can be used for data parallel processing in workers self.device_ids = device_ids self.cuda = cuda @@ -297,33 +288,11 @@ def __init__( local_files_only=self._local_files_only, specific_model_path=self._specific_model_path, ) - self._coreml_dir = self._download_coreml_model() + self._init_coreml(kwargs.get("coreml_lengths")) if not self.lazy_load: self.load_onnx_model() - def _download_coreml_model(self) -> Path | None: - if not requests_coreml(self.providers) or self._specific_model_path: - return None - coreml = self.model_description.coreml - if coreml is None: - warnings.warn( - f"{self.model_name} has no CoreML support, CoreML may run it slower than the CPU", - stacklevel=3, - ) - return None - if coreml.sources is None: - return self._model_dir - export = replace( - self.model_description, - sources=coreml.sources, - model_file=coreml.model_file or self.model_description.model_file, - additional_files=[], - ) - return self.download_model( - export, str(self.cache_dir), local_files_only=self._local_files_only - ) - def embed( self, documents: str | Iterable[str], @@ -386,35 +355,9 @@ def _post_process_onnx_output( raise ValueError(f"Unsupported embedding shape: {embeddings.shape}") return normalize(processed_embeddings) - def _batch_token_budget(self) -> int | None: - # CoreML pads batches to fixed shapes, smaller batches would only waste them - if self._coreml_dir is not None: - return None - return super()._batch_token_budget() - - def _get_worker_init_kwargs(self) -> dict[str, Any]: - kwargs = super()._get_worker_init_kwargs() - if self._coreml_lengths is not None: - kwargs["coreml_lengths"] = self._coreml_lengths - if self._max_batch_tokens is not None: - kwargs["max_batch_tokens"] = self._max_batch_tokens - return kwargs - - def _run_session( - self, onnx_input: dict[str, Any], onnx_output_names: list[str] | None = None - ) -> list[NumpyArray]: - if self._coreml_runner is not None: - return self._coreml_runner.run(onnx_input, onnx_output_names) - return self._run_model_with_shrinkage(onnx_output_names, onnx_input) - - def _run_model( - self, onnx_input: dict[str, Any], onnx_output_names: list[str] | None = None - ) -> NumpyArray: - return self._run_session(onnx_input, onnx_output_names)[0] - def load_onnx_model(self) -> None: if self._coreml_dir is not None: - self._load_coreml_model(self._coreml_dir) + self._load_coreml_model() return self._load_onnx_model( model_dir=self._model_dir, @@ -427,41 +370,6 @@ def load_onnx_model(self) -> None: additional_files=self.model_description.additional_files, ) - def _load_coreml_model(self, model_dir: Path) -> None: - coreml = self.model_description.coreml - assert coreml is not None - model_file = coreml.model_file or self.model_description.model_file - additional_files = [] if coreml.sources else self.model_description.additional_files - # the CPU session runs the batches too small for CoreML - self._load_onnx_model( - model_dir=model_dir, - model_file=model_file, - threads=self.threads, - providers=["CPUExecutionProvider"], - extra_session_options=self._extra_session_options, - additional_files=additional_files, - ) - try: - model_path = link_external_data(model_dir, model_file, additional_files) - except OSError: - model_path = model_dir / model_file - assert self.model is not None and self.tokenizer is not None and self.cache_dir - self._coreml_runner = CoreMLRunner( - model_path=model_path, - cache_dir=Path(self.cache_dir) / "coreml" / self.model_name.replace("/", "--"), - cpu_session=self.model, - options=coreml_options(self.providers), # type: ignore[arg-type] - max_length=(self.tokenizer.truncation or {}).get("max_length"), - lengths=self._coreml_lengths, - cpu_max_tokens=super()._batch_token_budget(), - ) - - def warmup(self, lengths: Sequence[int] | None = None) -> None: - if self.model is None: - self.load_onnx_model() - if self._coreml_runner is not None: - self._coreml_runner.warmup(lengths) - def token_count( self, texts: str | Iterable[str], batch_size: int = 1024, **kwargs: Any ) -> int: diff --git a/fastembed/text/onnx_text_model.py b/fastembed/text/onnx_text_model.py index 670b57ec0..c785020e0 100644 --- a/fastembed/text/onnx_text_model.py +++ b/fastembed/text/onnx_text_model.py @@ -8,6 +8,7 @@ from numpy.typing import NDArray from tokenizers import Encoding, Tokenizer +from fastembed.common.coreml import requests_coreml from fastembed.common.onnx_model import EmbeddingWorker, OnnxModel, OnnxOutputContext, T from fastembed.common.preprocessor_utils import load_tokenizer from fastembed.common.types import Device, NumpyArray, OnnxProvider @@ -174,7 +175,9 @@ def _embed_documents( if parallel == 0: parallel = available_core_count() - start_method = "forkserver" if "forkserver" in get_all_start_methods() else "spawn" + # Metal can't compile in a forked process, so CoreML workers are spawned + forkserver = "forkserver" in get_all_start_methods() and not requests_coreml(providers) + start_method = "forkserver" if forkserver else "spawn" params = { "model_name": model_name, "cache_dir": cache_dir, From 6a0aaeef46d2128cbcb4f5987db7d003a6395e27 Mon Sep 17 00:00:00 2001 From: anush008 Date: Tue, 1 Dec 2026 23:29:41 +0530 Subject: [PATCH 06/12] chore: run CoreML in the current process, ignoring parallel --- fastembed/common/coreml.py | 10 +--------- fastembed/text/onnx_text_model.py | 7 +++---- 2 files changed, 4 insertions(+), 13 deletions(-) diff --git a/fastembed/common/coreml.py b/fastembed/common/coreml.py index 065faafc1..b1a6ac388 100644 --- a/fastembed/common/coreml.py +++ b/fastembed/common/coreml.py @@ -73,7 +73,7 @@ def _create_session(self, length: int) -> ort.InferenceSession: cache = self.cache_dir / f"{COREML_ROWS}x{length}" options = {**self.options, "ModelCacheDirectory": str(cache)} cache.parent.mkdir(parents=True, exist_ok=True) - # parallel workers compile one at a time, the others load the compiled model + # processes compile one at a time, the others load the compiled model with open(cache.with_suffix(".lock"), "w") as lock: fcntl.flock(lock, fcntl.LOCK_EX) if not cache.exists(): @@ -253,11 +253,3 @@ def _batch_token_budget(self) -> int | None: if self._coreml_dir is not None and self._max_batch_tokens is None: return None return super()._batch_token_budget() - - def _get_worker_init_kwargs(self) -> dict[str, Any]: - kwargs = super()._get_worker_init_kwargs() - if self._coreml_lengths is not None: - kwargs["coreml_lengths"] = self._coreml_lengths - if self._max_batch_tokens is not None: - kwargs["max_batch_tokens"] = self._max_batch_tokens - return kwargs diff --git a/fastembed/text/onnx_text_model.py b/fastembed/text/onnx_text_model.py index c785020e0..3e8ee8c5d 100644 --- a/fastembed/text/onnx_text_model.py +++ b/fastembed/text/onnx_text_model.py @@ -153,7 +153,8 @@ def _embed_documents( if isinstance(documents, list) and len(documents) < batch_size: is_small = True - if parallel is None or is_small: + # CoreML shares one GPU, so workers don't run faster but compile and load it again each + if parallel is None or is_small or requests_coreml(providers): if not hasattr(self, "model") or self.model is None: self.load_onnx_model() yield from restore_order( @@ -175,9 +176,7 @@ def _embed_documents( if parallel == 0: parallel = available_core_count() - # Metal can't compile in a forked process, so CoreML workers are spawned - forkserver = "forkserver" in get_all_start_methods() and not requests_coreml(providers) - start_method = "forkserver" if forkserver else "spawn" + start_method = "forkserver" if "forkserver" in get_all_start_methods() else "spawn" params = { "model_name": model_name, "cache_dir": cache_dir, From fc13ac709d400b15d2d6d26635fe1ae4e3d31635 Mon Sep 17 00:00:00 2001 From: George Date: Wed, 2 Dec 2026 18:08:34 +0700 Subject: [PATCH 07/12] fix: fall back when the CoreML export or cache is unavailable (#930) * fix: fall back when the CoreML export or cache is unavailable * tests: remove CoreML fallback tests * fix: lock CoreML session creation and load all lengths in the constructor * fix: default to 3 CoreML lengths, document their cost and shorten load logs --- README.md | 17 ++++- fastembed/common/coreml.py | 105 ++++++++++++++++++++++++------- fastembed/text/text_embedding.py | 9 ++- 3 files changed, 105 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index c811f95d6..ec5a8f210 100644 --- a/README.md +++ b/README.md @@ -242,11 +242,24 @@ embedding_model = TextEmbedding( model_name="BAAI/bge-small-en-v1.5", providers=["CoreMLExecutionProvider"] ) -embedding_model.warmup() print("The model BAAI/bge-small-en-v1.5 is ready to use on Apple Silicon.") ``` -The model is compiled for the GPU on first use, which can take a few minutes for larger models. `warmup()` does it upfront. +Creating the model compiles it for the GPU the first time, which can take a few minutes for larger models, and loads the compiled model from the cache after that. With `lazy_load=True`, this happens when the model is first used instead, or when you call `warmup()`. + +CoreML runs batches of 16 texts padded to a fixed number of tokens, and FastEmbed compiles a version of the model for each of these lengths: 64, 256, and 512 tokens by default. Each length takes its own memory, load time, and disk space. For `BAAI/bge-base-en-v1.5` on an M2 Max, each one adds about 0.45 GB of memory, 30 seconds of load time, and 1.5 GB of disk space. More lengths waste less work on padding, which speeds up texts of mixed lengths, while fewer lengths save memory. Set them with `coreml_lengths`: + +```python +embedding_model = TextEmbedding( + model_name="BAAI/bge-base-en-v1.5", + providers=["CoreMLExecutionProvider"], + coreml_lengths=(64, 128, 256, 384, 512), # mixed lengths about 6% faster, 0.9 GB more memory +) +``` + +Fewer than 4 texts at a time, such as single queries, run on the CPU, and so do texts longer than the largest length. + +The compiled models are stored in `cache_dir`. By default it's a temporary directory that macOS can clear, which means compiling again, so pass a permanent `cache_dir` or set `FASTEMBED_CACHE_PATH`. ## Usage with Qdrant diff --git a/fastembed/common/coreml.py b/fastembed/common/coreml.py index b1a6ac388..390807a17 100644 --- a/fastembed/common/coreml.py +++ b/fastembed/common/coreml.py @@ -1,3 +1,6 @@ +import os +import threading +import time import warnings from collections.abc import Callable, Iterable, Sequence from dataclasses import replace @@ -16,7 +19,9 @@ COREML_PROVIDER = "CoreMLExecutionProvider" COREML_ROWS = 16 -COREML_LENGTHS = (64, 128, 256, 384, 512) +# each length is its own compiled model with another copy of the weights. Without 128 and 384, +# bge-base took 28% less memory, ran as fast on short texts and 6% slower on mixed lengths +COREML_LENGTHS = (64, 256, 512) # smaller batches, e.g. single queries, are faster on the CPU than padded to 16 rows COREML_MIN_ROWS = 4 DEFAULT_COREML_OPTIONS = {"ModelFormat": "MLProgram", "MLComputeUnits": "CPUAndGPU"} @@ -61,42 +66,80 @@ def __init__( self.options = options self.inputs = cpu_session.get_inputs() self.sessions: dict[int, ort.InferenceSession] = {} + self._sessions_lock = threading.Lock() + # False once the cache couldn't be written, e.g. a read-only cache_dir + self._cache_writable = True def _create_session(self, length: int) -> ort.InferenceSession: - import fcntl # CoreML is macOS only, fcntl isn't on Windows - batch_dim, length_dim = self.inputs[0].shape[:2] session_options = ort.SessionOptions() session_options.add_free_dimension_override_by_name(batch_dim, COREML_ROWS) session_options.add_free_dimension_override_by_name(length_dim, length) + + def create(options: dict[str, Any]) -> ort.InferenceSession: + return ort.InferenceSession( + self.model_path, + sess_options=session_options, + providers=[(COREML_PROVIDER, options), "CPUExecutionProvider"], + ) + # onnxruntime keys the cache by the model file, not by the overridden shape cache = self.cache_dir / f"{COREML_ROWS}x{length}" - options = {**self.options, "ModelCacheDirectory": str(cache)} - cache.parent.mkdir(parents=True, exist_ok=True) - # processes compile one at a time, the others load the compiled model - with open(cache.with_suffix(".lock"), "w") as lock: - fcntl.flock(lock, fcntl.LOCK_EX) + lock = self._lock_cache(cache) + if lock is None: + # onnxruntime compiles into a temporary directory instead + return create(self.options) + try: if not cache.exists(): logger.info( f"Compiling {self.model_path} for CoreML at {length} tokens into {cache}" ) - return ort.InferenceSession( - self.model_path, - sess_options=session_options, - providers=[(COREML_PROVIDER, options), "CPUExecutionProvider"], + return create({**self.options, "ModelCacheDirectory": str(cache)}) + finally: + os.close(lock) + + def _lock_cache(self, cache: Path) -> int | None: + """Locks `cache`, so that processes compile one at a time and the others load the + compiled model. Returns the lock's file descriptor, None if the cache can't be written.""" + if not self._cache_writable: + return None + lock = None + try: + cache.parent.mkdir(parents=True, exist_ok=True) + lock = os.open(cache.with_suffix(".lock"), os.O_WRONLY | os.O_CREAT, 0o644) + import fcntl # CoreML is macOS only, fcntl isn't on Windows + + fcntl.flock(lock, fcntl.LOCK_EX) + return lock + except OSError as error: + if lock is not None: + os.close(lock) + self._cache_writable = False + logger.warning( + f"Could not write the CoreML cache in {self.cache_dir}: {error}. CoreML compiles " + f"{self.model_path} again in every process, which can take minutes. Pass a " + "writable cache_dir, or a writable ModelCacheDirectory in the " + f"{COREML_PROVIDER} options." ) + return None def session(self, length: int) -> ort.InferenceSession: if length not in self.sessions: - self.sessions[length] = self._create_session(length) + # threads that need a length first, e.g. in a web server, would each load it + with self._sessions_lock: + if length not in self.sessions: + self.sessions[length] = self._create_session(length) return self.sessions[length] def warmup(self, lengths: Sequence[int] | None = None) -> None: - """Compiles `lengths`, all by default, running one batch each: CoreML finishes - compiling for the device on the first run.""" - for length in lengths or self.lengths: - if length not in self.lengths: - raise ValueError(f"{length} is not one of the CoreML lengths {self.lengths}") + """Loads `lengths` that aren't loaded yet, all by default, running one batch each: + CoreML finishes compiling for the device on the first run.""" + lengths = lengths or self.lengths + if unknown := [length for length in lengths if length not in self.lengths]: + raise ValueError(f"{unknown} aren't among the CoreML lengths {self.lengths}") + pending = [length for length in dict.fromkeys(lengths) if length not in self.sessions] + for number, length in enumerate(pending, 1): + start = time.perf_counter() feed = { model_input.name: np.full( (COREML_ROWS, length), @@ -106,6 +149,10 @@ def warmup(self, lengths: Sequence[int] | None = None) -> None: for model_input in self.inputs } self.session(length).run(None, feed) + logger.info( + f"Loaded CoreML length {length} in {time.perf_counter() - start:.1f} s, " + f"{len(pending) - number} left" + ) def run( self, onnx_input: dict[str, NumpyArray], output_names: list[str] | None = None @@ -166,6 +213,7 @@ class CoreMLMixin(OnnxModel[NumpyArray], ModelManagement[DenseModelDescription]) providers: Sequence[OnnxProvider] | None threads: int | None cache_dir: str | None + lazy_load: bool _extra_session_options: dict[str, Any] _local_files_only: bool _specific_model_path: str | None @@ -196,9 +244,20 @@ def _init_coreml(self, lengths: Sequence[int] | None) -> None: model_file=coreml.model_file or self.model_description.model_file, additional_files=[], ) - self._coreml_dir = self.download_model( - export, str(self.cache_dir), local_files_only=self._local_files_only - ) + try: + self._coreml_dir = self.download_model( + export, str(self.cache_dir), local_files_only=self._local_files_only + ) + except (OSError, ValueError) as error: + # the model itself is there, so run it rather than fail, e.g. offline + warnings.warn( + f"Could not download {coreml.sources.hf}, the CoreML version of " + f"{self.model_name}, so the model runs on the CPU. To use CoreML, load it once " + "while huggingface.co (or an `HF_ENDPOINT` mirror) is reachable, without " + f"`local_files_only=True` or `HF_HUB_OFFLINE=1`. The error: {error}", + stacklevel=3, + ) + self.providers = ["CPUExecutionProvider"] def _load_coreml_model(self) -> None: coreml = self.model_description.coreml @@ -234,6 +293,10 @@ def _load_coreml_model(self) -> None: # releases the CPU session's memory after each call, as without CoreML cpu_run=super()._run_model_with_shrinkage, ) + if not self.lazy_load: + # ready once the constructor returns, as without CoreML, otherwise lengths load on + # first use or in warmup() + self._coreml_runner.warmup() def warmup(self, lengths: Sequence[int] | None = None) -> None: if getattr(self, "model", None) is None: diff --git a/fastembed/text/text_embedding.py b/fastembed/text/text_embedding.py index 367204dc2..a6e879372 100644 --- a/fastembed/text/text_embedding.py +++ b/fastembed/text/text_embedding.py @@ -127,8 +127,10 @@ def __init__( mmap (bool): For static models (minishlab potion), whether to memory-map the embedding matrix instead of reading it into memory. Defaults to False. coreml_lengths (Sequence[int]): For CoreML, the token lengths to compile. - Longer texts run on the CPU. Lengths over the model's limit are replaced - by the limit, e.g. 77 for CLIP. Defaults to (64, 128, 256, 384, 512). + Longer texts run on the CPU. Each length takes its own memory and load + time, while more lengths pad less. Lengths over the model's limit are + replaced by the limit, e.g. 77 for CLIP. The constructor loads all of them, + or with `lazy_load=True` each on first use. Defaults to (64, 256, 512). """ super().__init__(model_name, cache_dir, threads, **kwargs) if model_name.lower() == "jinaai/jina-embeddings-v2-base-de": @@ -243,7 +245,8 @@ def passage_embed(self, texts: Iterable[str], **kwargs: Any) -> Iterable[NumpyAr yield from self.model.passage_embed(texts, **kwargs) def warmup(self, lengths: Sequence[int] | None = None) -> None: - """Loads the model and, for CoreML, compiles `lengths` (all by default) up front. + """Loads the model and, for CoreML, loads `lengths` (all by default) up front, compiling + them the first time. Without `lazy_load=True`, the constructor already loads them all. `lengths` must be among the model's CoreML lengths, after the model's limit applies. """ From d2e1cdf14f9c245b195e08781445da5e89cabc30 Mon Sep 17 00:00:00 2001 From: George Date: Wed, 2 Dec 2026 19:12:02 +0700 Subject: [PATCH 08/12] fix: keep the CPU batch budget for texts longer than the CoreML lengths (#931) --- fastembed/common/coreml.py | 13 +++++++------ fastembed/common/onnx_model.py | 4 ++++ fastembed/common/utils.py | 8 +++++--- fastembed/text/onnx_text_model.py | 1 + fastembed/text/text_embedding.py | 9 +++++---- 5 files changed, 22 insertions(+), 13 deletions(-) diff --git a/fastembed/common/coreml.py b/fastembed/common/coreml.py index 390807a17..17a0dba9d 100644 --- a/fastembed/common/coreml.py +++ b/fastembed/common/coreml.py @@ -289,7 +289,7 @@ def _load_coreml_model(self) -> None: options=options, max_length=(self.tokenizer.truncation or {}).get("max_length"), lengths=self._coreml_lengths, - cpu_max_tokens=super()._batch_token_budget(), + cpu_max_tokens=self._batch_token_budget(), # releases the CPU session's memory after each call, as without CoreML cpu_run=super()._run_model_with_shrinkage, ) @@ -311,8 +311,9 @@ def _run_model_with_shrinkage( return self._coreml_runner.run(onnx_input, output_names) return super()._run_model_with_shrinkage(output_names, onnx_input) - def _batch_token_budget(self) -> int | None: - # CoreML pads batches to fixed shapes, smaller batches would only waste them - if self._coreml_dir is not None and self._max_batch_tokens is None: - return None - return super()._batch_token_budget() + def _unbudgeted_length(self) -> int: + # CoreML pads batches to fixed shapes, smaller batches would only waste them. Longer texts + # run on the CPU and keep its budget: a batch holds every text's per-token output + if self._coreml_runner is not None and self._max_batch_tokens is None: + return self._coreml_runner.lengths[-1] + return super()._unbudgeted_length() diff --git a/fastembed/common/onnx_model.py b/fastembed/common/onnx_model.py index a507c8329..6acdc483c 100644 --- a/fastembed/common/onnx_model.py +++ b/fastembed/common/onnx_model.py @@ -212,6 +212,10 @@ def _batch_token_budget(self) -> int | None: return self._max_batch_tokens or None return MAX_BATCH_TOKENS + def _unbudgeted_length(self) -> int: + """Batches of texts up to this many tokens hold `batch_size` texts despite the budget.""" + return 0 + @cached_property def _attention_heads(self) -> int | None: """Attention heads per layer from config.json, None when the model doesn't say.""" diff --git a/fastembed/common/utils.py b/fastembed/common/utils.py index b52f9f225..03483e792 100644 --- a/fastembed/common/utils.py +++ b/fastembed/common/utils.py @@ -100,6 +100,7 @@ def iter_length_sorted_windows( window_batches: int = 8, max_batch_tokens: int | None = None, attention_heads: int | None = None, + unbudgeted_length: int = 0, ) -> Iterable[list[tuple[list[int], list[T]]]]: """Batch texts of similar length together, sorting within windows of `window_batches` batches. @@ -114,7 +115,8 @@ def iter_length_sorted_windows( budget is multiplied by `ATTENTION_HEADS` / `attention_heads`: a model with fewer heads has less attention per text (heads x length x length scores), so it batches more texts for the same attention work, which onnxruntime's CPU attention, split over texts x heads, needs to keep - its threads busy. A single text always makes a batch. + its threads busy. A single text always makes a batch. Batches whose texts have at most + `unbudgeted_length` tokens ignore the budget, e.g. the lengths CoreML runs, padded to 16 rows. """ if batch_size < 1: raise ValueError(f"batch_size must be >= 1, got {batch_size}") @@ -127,8 +129,8 @@ def iter_length_sorted_windows( start = 0 while start < len(order): size = batch_size - if max_batch_tokens is not None: - longest = max(lengths[order[start]], 1) + longest = max(lengths[order[start]], 1) + if max_batch_tokens is not None and longest > unbudgeted_length: budget = max_batch_tokens if longest > ATTENTION_LENGTH: budget = max_batch_tokens * ATTENTION_HEADS // heads diff --git a/fastembed/text/onnx_text_model.py b/fastembed/text/onnx_text_model.py index 3e8ee8c5d..dd3dccd27 100644 --- a/fastembed/text/onnx_text_model.py +++ b/fastembed/text/onnx_text_model.py @@ -169,6 +169,7 @@ def _embed_documents( self._token_count, max_batch_tokens=self._batch_token_budget(), attention_heads=self._attention_heads, + unbudgeted_length=self._unbudgeted_length(), ) ) ) diff --git a/fastembed/text/text_embedding.py b/fastembed/text/text_embedding.py index a6e879372..e767bb085 100644 --- a/fastembed/text/text_embedding.py +++ b/fastembed/text/text_embedding.py @@ -127,10 +127,11 @@ def __init__( mmap (bool): For static models (minishlab potion), whether to memory-map the embedding matrix instead of reading it into memory. Defaults to False. coreml_lengths (Sequence[int]): For CoreML, the token lengths to compile. - Longer texts run on the CPU. Each length takes its own memory and load - time, while more lengths pad less. Lengths over the model's limit are - replaced by the limit, e.g. 77 for CLIP. The constructor loads all of them, - or with `lazy_load=True` each on first use. Defaults to (64, 256, 512). + Longer texts run on the CPU, batched by `max_batch_tokens` as without + CoreML. Each length takes its own memory and load time, while more lengths + pad less. Lengths over the model's limit are replaced by the limit, e.g. 77 + for CLIP. The constructor loads all of them, or with `lazy_load=True` each + on first use. Defaults to (64, 256, 512). """ super().__init__(model_name, cache_dir, threads, **kwargs) if model_name.lower() == "jinaai/jina-embeddings-v2-base-de": From 36152580b1c4e48aa791adebde30a7a893927ef9 Mon Sep 17 00:00:00 2001 From: George Date: Wed, 2 Dec 2026 20:44:18 +0700 Subject: [PATCH 09/12] fix: fall back quickly and quietly when the CoreML export can't be downloaded (#933) * fix: download the CoreML export once and quietly * fix: call the CoreML export the CoreML-compatible copy in the warning --- fastembed/common/coreml.py | 4 ++-- fastembed/common/model_management.py | 26 +++++++++++++++++++++++++- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/fastembed/common/coreml.py b/fastembed/common/coreml.py index 17a0dba9d..9dcbda606 100644 --- a/fastembed/common/coreml.py +++ b/fastembed/common/coreml.py @@ -246,12 +246,12 @@ def _init_coreml(self, lengths: Sequence[int] | None) -> None: ) try: self._coreml_dir = self.download_model( - export, str(self.cache_dir), local_files_only=self._local_files_only + export, str(self.cache_dir), optional=True, local_files_only=self._local_files_only ) except (OSError, ValueError) as error: # the model itself is there, so run it rather than fail, e.g. offline warnings.warn( - f"Could not download {coreml.sources.hf}, the CoreML version of " + f"Could not download {coreml.sources.hf}, the CoreML-compatible copy of " f"{self.model_name}, so the model runs on the CPU. To use CoreML, load it once " "while huggingface.co (or an `HF_ENDPOINT` mirror) is reachable, without " f"`local_files_only=True` or `HF_HUB_OFFLINE=1`. The error: {error}", diff --git a/fastembed/common/model_management.py b/fastembed/common/model_management.py index d3befee08..9bb5c4162 100644 --- a/fastembed/common/model_management.py +++ b/fastembed/common/model_management.py @@ -620,7 +620,9 @@ def _link_onnx_external_data(model: BaseModelDescription, model_dir: Path) -> Pa return model_dir @classmethod - def download_model(cls, model: T, cache_dir: str, retries: int = 3, **kwargs: Any) -> Path: + def download_model( + cls, model: T, cache_dir: str, retries: int = 3, optional: bool = False, **kwargs: Any + ) -> Path: """ Downloads a model from HuggingFace Hub or Google Cloud Storage. @@ -640,6 +642,10 @@ def download_model(cls, model: T, cache_dir: str, retries: int = 3, **kwargs: An ``` cache_dir (str): The path to the cache directory. retries: (int): The number of times to retry (including the first attempt) + optional (bool): Whether the caller can do without the model, e.g. the + CoreML-compatible copy of one. A model that isn't cached is then downloaded + from HuggingFace once, with no other sources and no error logs, and a failure + raises a ValueError for the caller to report. Returns: Path: The path to the downloaded model directory. @@ -688,6 +694,24 @@ def download_model(cls, model: T, cache_dir: str, retries: int = 3, **kwargs: An finally: enable_progress_bars() + if optional: + if local_files_only or not hf_source: + raise ValueError(f"Could not find {hf_source or model.model} in {cache_dir}") + try: + model_dir = Path( + cls.download_files_from_huggingface( + hf_source, + cache_dir=cache_dir, + extra_patterns=extra_patterns, + **({**kwargs, "force_download": True} if force_download else kwargs), + ) + ) + except _HF_DOWNLOAD_ERRORS as error: + raise ValueError(f"Could not download {hf_source}: {error}") from error + finally: + enable_progress_bars() + return cls._link_onnx_external_data(model, model_dir) + sleep = 3.0 while retries > 0: retries -= 1 From 69540003e5d8bc050b04322477f24a9b107deab7 Mon Sep 17 00:00:00 2001 From: George Date: Wed, 2 Dec 2026 20:49:18 +0700 Subject: [PATCH 10/12] fix: run each CoreML batch of long texts in one CPU run (#932) --- fastembed/common/coreml.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/fastembed/common/coreml.py b/fastembed/common/coreml.py index 9dcbda606..78fa8bb7b 100644 --- a/fastembed/common/coreml.py +++ b/fastembed/common/coreml.py @@ -16,6 +16,7 @@ from fastembed.common.onnx_external_data import link_external_data from fastembed.common.onnx_model import OnnxModel from fastembed.common.types import NumpyArray, OnnxProvider +from fastembed.common.utils import ATTENTION_HEADS COREML_PROVIDER = "CoreMLExecutionProvider" COREML_ROWS = 16 @@ -282,6 +283,13 @@ def _load_coreml_model(self) -> None: cache_dir = Path( options.pop("ModelCacheDirectory", None) or Path(self.cache_dir) / "coreml" ) + cpu_max_tokens = self._batch_token_budget() + if cpu_max_tokens is not None: + # batching gives long texts more tokens when the model has fewer attention heads, so + # the CPU runs each batch of them in one go + cpu_max_tokens = ( + cpu_max_tokens * ATTENTION_HEADS // (self._attention_heads or ATTENTION_HEADS) + ) self._coreml_runner = CoreMLRunner( model_path=model_path, cache_dir=cache_dir / self.model_name.replace("/", "--"), @@ -289,7 +297,7 @@ def _load_coreml_model(self) -> None: options=options, max_length=(self.tokenizer.truncation or {}).get("max_length"), lengths=self._coreml_lengths, - cpu_max_tokens=self._batch_token_budget(), + cpu_max_tokens=cpu_max_tokens, # releases the CPU session's memory after each call, as without CoreML cpu_run=super()._run_model_with_shrinkage, ) From 6c872cb3b661a2abb656ad2b46a0015e3a0085e4 Mon Sep 17 00:00:00 2001 From: George Panchuk Date: Wed, 2 Dec 2026 20:53:41 +0700 Subject: [PATCH 11/12] docs: list CoreML models in the README and shorten its example --- README.md | 25 ++++++++----------------- 1 file changed, 8 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index ec5a8f210..9d1f17e6d 100644 --- a/README.md +++ b/README.md @@ -231,31 +231,22 @@ print("The model BAAI/bge-small-en-v1.5 is ready to use on a GPU.") ### On Apple Silicon -FastEmbed supports running on Apple Silicon GPUs for accelerated inference. - -No extra installation is needed. +FastEmbed can run `TextEmbedding` models on Apple Silicon GPUs through CoreML, with no extra installation: ```python from fastembed import TextEmbedding -embedding_model = TextEmbedding( - model_name="BAAI/bge-small-en-v1.5", - providers=["CoreMLExecutionProvider"] -) -print("The model BAAI/bge-small-en-v1.5 is ready to use on Apple Silicon.") +embedding_model = TextEmbedding("BAAI/bge-small-en-v1.5", providers=["CoreMLExecutionProvider"]) + +# the models that support CoreML +print([model["model"] for model in TextEmbedding.list_supported_models() if model["coreml"]]) ``` -Creating the model compiles it for the GPU the first time, which can take a few minutes for larger models, and loads the compiled model from the cache after that. With `lazy_load=True`, this happens when the model is first used instead, or when you call `warmup()`. +Other `TextEmbedding` models print a warning, since CoreML may run them slower than the CPU. Sparse, late interaction, image, and reranking models have no CoreML support. -CoreML runs batches of 16 texts padded to a fixed number of tokens, and FastEmbed compiles a version of the model for each of these lengths: 64, 256, and 512 tokens by default. Each length takes its own memory, load time, and disk space. For `BAAI/bge-base-en-v1.5` on an M2 Max, each one adds about 0.45 GB of memory, 30 seconds of load time, and 1.5 GB of disk space. More lengths waste less work on padding, which speeds up texts of mixed lengths, while fewer lengths save memory. Set them with `coreml_lengths`: +Creating the model compiles it for the GPU the first time, which can take a few minutes for larger models, and loads the compiled model from the cache after that. With `lazy_load=True`, this happens when the model is first used instead, or when you call `warmup()`. -```python -embedding_model = TextEmbedding( - model_name="BAAI/bge-base-en-v1.5", - providers=["CoreMLExecutionProvider"], - coreml_lengths=(64, 128, 256, 384, 512), # mixed lengths about 6% faster, 0.9 GB more memory -) -``` +CoreML runs batches of 16 texts padded to a fixed number of tokens, and FastEmbed compiles a version of the model for each of these lengths: 64, 256, and 512 tokens by default. Each length takes its own memory, load time, and disk space. For `BAAI/bge-base-en-v1.5` on an M2 Max, each one adds about 0.45 GB of memory, 30 seconds of load time, and 1.5 GB of disk space. More lengths waste less work on padding, which speeds up texts of mixed lengths, while fewer lengths save memory. Set them with `coreml_lengths`: for example, `coreml_lengths=(64, 128, 256, 384, 512)` makes texts of mixed lengths about 6% faster and takes 0.9 GB more memory. Fewer than 4 texts at a time, such as single queries, run on the CPU, and so do texts longer than the largest length. From 6fa51afd251e755be61f10c930216c3536236907 Mon Sep 17 00:00:00 2001 From: George Date: Wed, 2 Dec 2026 21:50:18 +0700 Subject: [PATCH 12/12] fix: ignore parallel only for CoreML text models, with a warning (#934) * fix: ignore parallel only for CoreML text models, with a warning * fix: resolve parallel through a general hook that CoreML overrides --- fastembed/common/coreml.py | 10 ++++++++++ fastembed/common/onnx_model.py | 4 ++++ fastembed/text/onnx_embedding.py | 1 + fastembed/text/onnx_text_model.py | 5 ++--- fastembed/text/text_embedding.py | 1 + 5 files changed, 18 insertions(+), 3 deletions(-) diff --git a/fastembed/common/coreml.py b/fastembed/common/coreml.py index 78fa8bb7b..4c48ca32d 100644 --- a/fastembed/common/coreml.py +++ b/fastembed/common/coreml.py @@ -312,6 +312,16 @@ def warmup(self, lengths: Sequence[int] | None = None) -> None: if self._coreml_runner is not None: self._coreml_runner.warmup(lengths) + def _resolve_parallel(self, parallel: int | None) -> int | None: + if parallel is None or self._coreml_dir is None: + return super()._resolve_parallel(parallel) + warnings.warn( + f"parallel={parallel} is ignored with CoreML, which runs in this process: worker " + "processes would each compile and load the model again, to share one GPU.", + stacklevel=5, + ) + return None + def _run_model_with_shrinkage( self, output_names: list[str] | None, onnx_input: dict[str, Any] ) -> list[Any]: diff --git a/fastembed/common/onnx_model.py b/fastembed/common/onnx_model.py index 6acdc483c..10b04ff92 100644 --- a/fastembed/common/onnx_model.py +++ b/fastembed/common/onnx_model.py @@ -216,6 +216,10 @@ def _unbudgeted_length(self) -> int: """Batches of texts up to this many tokens hold `batch_size` texts despite the budget.""" return 0 + def _resolve_parallel(self, parallel: int | None) -> int | None: + """The `parallel` to embed with: as requested, or None where worker processes can't help.""" + return parallel + @cached_property def _attention_heads(self) -> int | None: """Attention heads per layer from config.json, None when the model doesn't say.""" diff --git a/fastembed/text/onnx_embedding.py b/fastembed/text/onnx_embedding.py index c7f43403d..228ecd63f 100644 --- a/fastembed/text/onnx_embedding.py +++ b/fastembed/text/onnx_embedding.py @@ -311,6 +311,7 @@ def embed( If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. If 0, use all available cores. If None, don't use data-parallel processing, use default onnxruntime threading instead. + Ignored with CoreML, which runs in this process. Returns: List of embeddings, one per document diff --git a/fastembed/text/onnx_text_model.py b/fastembed/text/onnx_text_model.py index dd3dccd27..76c600c00 100644 --- a/fastembed/text/onnx_text_model.py +++ b/fastembed/text/onnx_text_model.py @@ -8,7 +8,6 @@ from numpy.typing import NDArray from tokenizers import Encoding, Tokenizer -from fastembed.common.coreml import requests_coreml from fastembed.common.onnx_model import EmbeddingWorker, OnnxModel, OnnxOutputContext, T from fastembed.common.preprocessor_utils import load_tokenizer from fastembed.common.types import Device, NumpyArray, OnnxProvider @@ -144,6 +143,7 @@ def _embed_documents( extra_session_options: dict[str, Any] | None = None, **kwargs: Any, ) -> Iterable[T]: + parallel = self._resolve_parallel(parallel) is_small = False if isinstance(documents, str): @@ -153,8 +153,7 @@ def _embed_documents( if isinstance(documents, list) and len(documents) < batch_size: is_small = True - # CoreML shares one GPU, so workers don't run faster but compile and load it again each - if parallel is None or is_small or requests_coreml(providers): + if parallel is None or is_small: if not hasattr(self, "model") or self.model is None: self.load_onnx_model() yield from restore_order( diff --git a/fastembed/text/text_embedding.py b/fastembed/text/text_embedding.py index e767bb085..dd1fe61e8 100644 --- a/fastembed/text/text_embedding.py +++ b/fastembed/text/text_embedding.py @@ -212,6 +212,7 @@ def embed( If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. If 0, use all available cores. If None, don't use data-parallel processing, use default onnxruntime threading instead. + Ignored with CoreML, which runs in this process. Returns: List of embeddings, one per document