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
17 changes: 15 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
105 changes: 84 additions & 21 deletions fastembed/common/coreml.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import os
import threading
import time
import warnings
from collections.abc import Callable, Iterable, Sequence
from dataclasses import replace
Expand All @@ -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"}
Expand Down Expand Up @@ -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),
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
9 changes: 6 additions & 3 deletions fastembed/text/text_embedding.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down Expand Up @@ -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.
"""
Expand Down