diff --git a/README.md b/README.md index dd6e24b8..9d1f17e6 100644 --- a/README.md +++ b/README.md @@ -229,6 +229,29 @@ print("The model BAAI/bge-small-en-v1.5 is ready to use on a GPU.") ``` +### On Apple Silicon + +FastEmbed can run `TextEmbedding` models on Apple Silicon GPUs through CoreML, with no extra installation: + +```python +from fastembed import TextEmbedding + +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"]]) +``` + +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. + +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`: 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. + +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 Installation with Qdrant Client in Python: diff --git a/fastembed/common/coreml.py b/fastembed/common/coreml.py new file mode 100644 index 00000000..4c48ca32 --- /dev/null +++ b/fastembed/common/coreml.py @@ -0,0 +1,337 @@ +import os +import threading +import time +import warnings +from collections.abc import Callable, Iterable, Sequence +from dataclasses import replace +from pathlib import Path +from typing import Any, cast + +import numpy as np +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 +from fastembed.common.utils import ATTENTION_HEADS + +COREML_PROVIDER = "CoreMLExecutionProvider" +COREML_ROWS = 16 +# 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"} + + +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, + 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): + 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_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] = {} + 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: + 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}" + 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 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: + # 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: + """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), + 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) + 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 + ) -> list[NumpyArray]: + 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 + ) -> list[NumpyArray]: + rows, width = chunk["input_ids"].shape + 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) + # 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))) + 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 + + 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_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)] + + +class CoreMLMixin(OnnxModel[NumpyArray], ModelManagement[DenseModelDescription]): + model_name: str + model_description: 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 + + _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=[], + ) + try: + self._coreml_dir = self.download_model( + 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-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}", + stacklevel=3, + ) + self.providers = ["CPUExecutionProvider"] + + 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" + ) + 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("/", "--"), + cpu_session=self.model, + options=options, + max_length=(self.tokenizer.truncation or {}).get("max_length"), + lengths=self._coreml_lengths, + 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, + ) + 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: + self.load_onnx_model() + 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]: + 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 _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/model_description.py b/fastembed/common/model_description.py index 0c539fd8..4f439d95 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/common/model_management.py b/fastembed/common/model_management.py index d3befee0..9bb5c416 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 diff --git a/fastembed/common/onnx_model.py b/fastembed/common/onnx_model.py index a507c832..10b04ff9 100644 --- a/fastembed/common/onnx_model.py +++ b/fastembed/common/onnx_model.py @@ -212,6 +212,14 @@ 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 + + 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/common/utils.py b/fastembed/common/utils.py index b52f9f22..03483e79 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/clip_embedding.py b/fastembed/text/clip_embedding.py index abe0b1af..72f1b20e 100644 --- a/fastembed/text/clip_embedding.py +++ b/fastembed/text/clip_embedding.py @@ -1,7 +1,7 @@ from collections.abc import Iterable from typing import Any -from fastembed.common.model_description import DenseModelDescription, ModelSource +from fastembed.common.model_description import CoreMLModel, DenseModelDescription, ModelSource from fastembed.common.onnx_model import OnnxOutputContext from fastembed.common.types import NumpyArray from fastembed.text.onnx_embedding import OnnxTextEmbedding, OnnxTextEmbeddingWorker @@ -18,6 +18,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 dda0d36b..228ecd63 100644 --- a/fastembed/text/onnx_embedding.py +++ b/fastembed/text/onnx_embedding.py @@ -1,7 +1,8 @@ from collections.abc import Iterable, Sequence from typing import Any -from fastembed.common.model_description import DenseModelDescription, ModelSource +from fastembed.common.coreml import CoreMLMixin +from fastembed.common.model_description import CoreMLModel, DenseModelDescription, ModelSource 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 @@ -23,6 +24,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", @@ -38,6 +42,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", @@ -50,6 +57,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", @@ -65,6 +73,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", @@ -77,6 +88,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", @@ -92,6 +106,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", @@ -104,6 +121,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", @@ -116,6 +134,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", @@ -128,6 +147,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", @@ -140,6 +160,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", @@ -164,6 +185,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", @@ -193,7 +215,7 @@ ] -class OnnxTextEmbedding(TextEmbeddingBase, OnnxTextModel[NumpyArray]): +class OnnxTextEmbedding(CoreMLMixin, TextEmbeddingBase, OnnxTextModel[NumpyArray]): """Implementation of the Flag Embedding model.""" @classmethod @@ -266,6 +288,7 @@ def __init__( local_files_only=self._local_files_only, specific_model_path=self._specific_model_path, ) + self._init_coreml(kwargs.get("coreml_lengths")) if not self.lazy_load: self.load_onnx_model() @@ -288,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 @@ -333,6 +357,9 @@ def _post_process_onnx_output( return normalize(processed_embeddings) def load_onnx_model(self) -> None: + if self._coreml_dir is not None: + self._load_coreml_model() + return self._load_onnx_model( model_dir=self._model_dir, model_file=self.model_description.model_file, diff --git a/fastembed/text/onnx_text_model.py b/fastembed/text/onnx_text_model.py index 670b57ec..76c600c0 100644 --- a/fastembed/text/onnx_text_model.py +++ b/fastembed/text/onnx_text_model.py @@ -143,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): @@ -167,6 +168,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/pooled_embedding.py b/fastembed/text/pooled_embedding.py index 1b25fb06..5fa255c6 100644 --- a/fastembed/text/pooled_embedding.py +++ b/fastembed/text/pooled_embedding.py @@ -4,7 +4,7 @@ import numpy as np from numpy.typing import NDArray -from fastembed.common.model_description import DenseModelDescription, ModelSource +from fastembed.common.model_description import CoreMLModel, DenseModelDescription, ModelSource from fastembed.common.onnx_model import OnnxOutputContext from fastembed.common.types import NumpyArray from fastembed.common.utils import mean_pooling @@ -22,6 +22,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", @@ -46,6 +47,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", @@ -58,6 +60,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", @@ -70,6 +76,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", @@ -85,6 +92,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 01d0c34e..aac98f62 100644 --- a/fastembed/text/pooled_normalized_embedding.py +++ b/fastembed/text/pooled_normalized_embedding.py @@ -1,7 +1,7 @@ from collections.abc import Iterable from typing import Any -from fastembed.common.model_description import DenseModelDescription, ModelSource +from fastembed.common.model_description import CoreMLModel, DenseModelDescription, ModelSource from fastembed.common.onnx_model import OnnxOutputContext from fastembed.common.types import NumpyArray from fastembed.common.utils import normalize @@ -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 59029c2d..d6cbd744 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 -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 08dff73e..dd1fe61e 100644 --- a/fastembed/text/text_embedding.py +++ b/fastembed/text/text_embedding.py @@ -126,6 +126,12 @@ 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, 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": @@ -206,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 @@ -239,6 +246,14 @@ 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, 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. + """ + 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 8f3e318e..5462ac71 100644 --- a/fastembed/text/text_embedding_base.py +++ b/fastembed/text/text_embedding_base.py @@ -1,4 +1,4 @@ -from collections.abc import Iterable +from collections.abc import Iterable, Sequence from typing import Any from fastembed.common.model_description import DenseModelDescription @@ -74,3 +74,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."""