Repository navigation
feat: Run text embeddings on the Apple GPU with CoreML #916
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
b8ef43c
perf: run text embeddings on the Apple GPU with CoreML
anush008 e6d2b57
Merge remote-tracking branch 'origin/main' into perf/coreml-gpu
anush008 69da09a
fix: use np.flatnonzero so mypy passes with numpy 2.4 stubs
anush008 8cf9439
chore: Address review
anush008 0978d6c
chore: forward max_batch_tokens to CoreML workers
anush008 68b21a0
refactor: move CoreML support into CoreMLMixin
anush008 6a0aaee
chore: run CoreML in the current process, ignoring parallel
anush008 fc13ac7
fix: fall back when the CoreML export or cache is unavailable (#930)
joein d2e1cdf
fix: keep the CPU batch budget for texts longer than the CoreML lengt…
joein 3615258
fix: fall back quickly and quietly when the CoreML export can't be do…
joein 6954000
fix: run each CoreML batch of long texts in one CPU run (#932)
joein 6c872cb
docs: list CoreML models in the README and shorten its example
joein 6fa51af
fix: ignore parallel only for CoreML text models, with a warning (#934)
joein File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
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