Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"]])
```

@anush008 anush008 Dec 2, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Live preview of this section (Removed the text blob below): https://github.com/qdrant/fastembed#on-apple-silicon

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:
Expand Down
337 changes: 337 additions & 0 deletions fastembed/common/coreml.py
Original file line number Diff line number Diff line change
@@ -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()
7 changes: 7 additions & 0 deletions fastembed/common/model_description.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"
Expand Down
Loading
Loading