EmbeddingEngine#

class scikitplot.corpus.EmbeddingEngine(model_name='paraphrase-multilingual-mpnet-base-v2', backend='sentence_transformers', custom_fn=None, cache_dir=None, enable_cache=True, batch_size=64, normalize=True, dtype=<class 'numpy.float32'>, show_progress_bar=False, device=None, model_revision='', custom_fn_id=None, cache_policy=None)[source]#

Multi-backend sentence embedding engine with SHA-256 file caching.

Produces a 2-D float32 numpy array of shape (n_texts, dim) for a list of input strings. Embeddings are cached to .npy files keyed by a content-addressed hash of the texts and model params so that unchanged corpora are served from disk in O(1).

Parameters:
model_namestr, optional

Embedding model identifier. Interpretation depends on backend. For sentence_transformers, any HuggingFace model name. For openai, any OpenAI embedding model name. Ignored when backend="custom". Default: "paraphrase-multilingual-mpnet-base-v2".

backend{“sentence_transformers”, “openai”, “custom”}, optional

Which embedding backend to use. Default: "sentence_transformers".

custom_fncallable or None, optional

User-supplied Callable[[list[str]], np.ndarray]. Required when backend="custom". Ignored otherwise.

cache_dirpathlib.Path or None, optional

Directory for .npy cache files. Created if absent. None uses ~/.cache/scikitplot/embeddings. Pass pathlib.Path(os.devnull) to disable caching.

enable_cachebool, optional

Set to False to completely disable file caching (always re-computes). Default: True.

batch_sizeint, optional

Number of texts per encoding batch. Relevant for sentence_transformers and openai backends. Default: 64.

normalizebool, optional

L2-normalise output vectors to unit norm (required for cosine / inner-product similarity search), for every backend. Default: True.

dtypenumpy.dtype, optional

Output dtype. Default: numpy.float32.

show_progress_barbool, optional

Show a tqdm progress bar during encoding (sentence_transformers only). Default: False.

devicestr or None, optional

PyTorch device for sentence_transformers ("cpu", "cuda", "mps"). None lets the library choose. Default: None.

model_revisionstr, optional

Model revision (commit, tag or branch). The sentence_transformers backend loads exactly this revision; every backend records it in the cache key and the embedding manifest. "" (default) is unpinned: the hub’s current version is loaded. Only a commit hash makes the disk cache exact for sentence_transformers; an empty value or a branch or tag (which can move) uses the cache only as cache_policy allows (by default it does not). For other backends the value is recorded, not sent: it is your statement of which model version the name stands for.

custom_fn_idstr or None, optional

Stable identity of custom_fn, e.g. "my-embedder/v3"; change it whenever the function’s output changes. It is what the disk cache and the embedding manifest know the provider by. None (default) means the provider is unidentified: its vectors are not disk-cached, and the manifest it stamps is unique to this engine instance, so documents embedded by two engines cannot be indexed together by accident. Only valid with backend="custom".

cache_policyCachePolicy or None, optional

How the disk cache treats an unpinned model and how big it may grow. None (default) is CachePolicy(): an unpinned model’s embeddings are computed, not cached, and the cache is unbounded.

Attributes:
VALID_BACKENDStuple of str

Class variable. All accepted backend names.

Raises:
ValueError

If backend="custom" but custom_fn is None, or custom_fn_id is given with another backend or is empty.

ValueError

If batch_size or dtype are invalid.

TypeError

If model_revision is not a str, or cache_policy is neither a CachePolicy nor None.

ImportError

At call time if the required backend library is not installed.

Parameters:

See also

scikitplot.corpus.pipeline.CorpusPipeline

Integrates this engine.

scikitplot.corpus._embeddings._multimodal_embedding.MultimodalEmbeddingEngine

Extends this engine with image, audio, and video modalities plus projection layer and LLM training export.

Notes

Thread safety: The internal model cache (_embed_fn) is initialised lazily and protected by a threading.Lock.

Cache identity: The cache key is content-addressed: the full input text plus model, revision, backend, provider identity, dtype and normalisation (see _make_cache_key). Source path and modification time are not part of it, so the same text is served from cache whether it came from a file or a URL. A custom provider is cached only when it carries a custom_fn_id; without one, two different functions would share a key.

Provenance: embed_documents stamps every document with the fingerprint of embedding_manifest, so an index refuses to rank vectors from two embedding generations against each other.

Normalisation: When normalize=True, every backend’s vectors are L2-normalised; sentence-transformers does it while encoding, the engine does it for the others. Zero-norm vectors (e.g. empty-string inputs) are left as zero vectors rather than producing NaN. The normalisation guard in RetrievalIndex will warn if any zero vectors are detected at search time.

Examples

Default usage (sentence_transformers):

>>> engine = EmbeddingEngine()
>>> texts = ["Hello world.", "Second sentence."]
>>> vecs = engine.embed(texts)
>>> vecs.shape
(2, 768)

Custom callable backend:

>>> import numpy as np
>>> engine = EmbeddingEngine(
...     backend="custom",
...     custom_fn=lambda texts: np.zeros((len(texts), 64), dtype=np.float32),
... )
>>> engine.embed(["Hello."]).shape
(1, 64)

With the disk cache (a custom provider needs an identity to be cached):

>>> engine = EmbeddingEngine(
...     backend="custom",
...     custom_fn=lambda texts: np.ones((len(texts), 4), dtype=np.float32),
...     custom_fn_id="ones/v1",
... )
>>> vecs, from_cache = engine.embed_with_cache(["Hello."])
VALID_BACKENDS: ClassVar[tuple[str, ...]] = ('sentence_transformers', 'openai', 'custom')#

Accepted backend values.

For image/audio/video embeddings use MultimodalEmbeddingEngine which supports "clip", "whisper", "wav2vec" in addition.

backend: str = 'sentence_transformers'#
batch_size: int = 64#
cache_dir: Path | None = None#
cache_policy: CachePolicy | None = None#
custom_fn: Callable[[List[str]], NDArray[float32]] | None = None#
custom_fn_id: str | None = None#
device: str | None = None#
dtype[source]#

alias of float32

embed(texts)[source]#

Compute embeddings for texts without caching.

Parameters:
textslist of str

Non-empty list of text strings. Empty strings produce zero vectors; they are not filtered here (filtering belongs in the pipeline).

Returns:
numpy.ndarray

Array of shape (len(texts), dim) with dtype self.dtype.

Raises:
ValueError

If texts is empty.

ImportError

If the required backend library is not installed.

Parameters:

texts (list[str])

Return type:

NDArray[float32]

Examples

>>> engine = EmbeddingEngine(
...     backend="custom",
...     custom_fn=lambda t: np.zeros((len(t), 32), dtype=np.float32),
... )
>>> engine.embed(["hello"]).shape
(1, 32)
embed_cached(texts, input_path=None)[source]#

Compute embeddings through the disk cache, and say what happened.

Parameters:
textslist of str

Text strings to embed.

input_pathpathlib.Path or None, optional

Source of texts, for diagnostics only.

Returns:
CachedEmbeddings

(embeddings, status, key, revision); status is a CacheStatus.

Raises:
ValueError

If texts is empty.

Parameters:
Return type:

CachedEmbeddings

Notes

User. The cache is consulted only when a hit is what this engine would compute: a sentence-transformers model pinned to a commit (model_revision, or resolved with CachePolicy(unpinned= "resolve")), a custom provider’s custom_fn_id, the stated model_revision of another backend, or, by your choice, CachePolicy(unpinned="allow"). Otherwise the embeddings are computed and the status says why the cache was bypassed (logged once per engine). A failed write is reported as STORE_FAILED, never raised.

Developer. A hit refreshes the entry’s modification time; after a store, enforce_bounds evicts least recently used entries.

Examples

>>> engine = EmbeddingEngine(
...     backend="custom",
...     custom_fn=lambda t: np.ones((len(t), 4), dtype=np.float32),
...     enable_cache=False,
... )
>>> engine.embed_cached(["Hello."]).status.value
'disabled'
embed_documents(documents, input_path=None)[source]#

Embed a list of CorpusDocument instances in-place (sets doc.embedding on each).

Parameters:
documentslist of CorpusDocument

Documents to embed. Each must have a non-empty text field.

input_pathpathlib.Path or None, optional

Source of the documents, for diagnostics only. Caching follows enable_cache and cache_policy (see embed_cached); the key is content-addressed.

Returns:
list of CorpusDocument

The same list with embedding and embedding_manifest_id populated (via replace() — originals are not mutated).

Parameters:
Return type:

list[Any]

Notes

Developer. embedding_manifest_id is what lets an index refuse vectors from two generations (RetrievalIndex._reject_mixed_manifests). Documents used to leave this method untagged, and untagged vectors are never compared, so the guard never fired: two providers’ vectors were built into one index and ranked against each other without error.

Examples

>>> docs = list(reader.get_documents())
>>> docs = engine.embed_documents(docs)
>>> docs[0].has_embedding
True
embed_with_cache(texts, input_path=None)[source]#

Compute embeddings through the content-addressed disk cache.

Parameters:
textslist of str

Text strings to embed.

input_pathpathlib.Path or None, optional

Source of texts, for diagnostics only: the cache key is content-addressed over texts and the model parameters, never the path or its mtime. None (a URL or in-memory source) is cached exactly like a file.

Returns:
embeddingsnumpy.ndarray

Array of shape (len(texts), dim).

from_cachebool

True if the result was loaded from disk cache.

Raises:
ValueError

If texts is empty.

Parameters:
Return type:

tuple[NDArray[float32], bool]

See also

embed_cached

The same call, reporting what it did.

Examples

>>> engine = EmbeddingEngine(
...     backend="custom",
...     custom_fn=lambda t: np.ones((len(t), 4), dtype=np.float32),
...     custom_fn_id="ones/v1",
...     enable_cache=False,
... )
>>> engine.embed_with_cache(["Hello."])[1]
False
embedding_manifest(dimension)[source]#

Describe the vectors this engine produces.

Parameters:
dimensionint

Vector length, known once the first vectors exist.

Returns:
EmbeddingManifest

provider is the backend; model the model name, or for a custom provider its custom_fn_id; revision the pinned revision or None; plus dimension, dtype and normalisation.

Raises:
ValueError

If dimension is not a positive integer.

Parameters:

dimension (int)

Return type:

EmbeddingManifest

Notes

User. Give a custom provider a custom_fn_id: an unidentified one is named after this engine instance (custom:unidentified:...), so documents embedded by two engines – even two engines wrapping the same function – are refused as different generations when indexed together. That is the safe reading of “no identity”: nothing proves the two produced comparable vectors.

enable_cache: bool = True#
model_name: str = 'paraphrase-multilingual-mpnet-base-v2'#
model_revision: str = ''#
normalize: bool = True#
show_progress_bar: bool = False#