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
float32numpy array of shape(n_texts, dim)for a list of input strings. Embeddings are cached to.npyfiles 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. Forsentence_transformers, any HuggingFace model name. Foropenai, any OpenAI embedding model name. Ignored whenbackend="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 whenbackend="custom". Ignored otherwise.- cache_dirpathlib.Path or None, optional
Directory for
.npycache files. Created if absent.Noneuses~/.cache/scikitplot/embeddings. Passpathlib.Path(os.devnull)to disable caching.- enable_cachebool, optional
Set to
Falseto completely disable file caching (always re-computes). Default:True.- batch_sizeint, optional
Number of texts per encoding batch. Relevant for
sentence_transformersandopenaibackends. 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").Nonelets 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 ascache_policyallows (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 withbackend="custom".- cache_policyCachePolicy or None, optional
How the disk cache treats an unpinned model and how big it may grow.
None(default) isCachePolicy(): 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"butcustom_fnisNone, orcustom_fn_idis given with another backend or is empty.- ValueError
If
batch_sizeordtypeare invalid.- TypeError
If
model_revisionis not a str, orcache_policyis neither aCachePolicynorNone.- ImportError
At call time if the required backend library is not installed.
- Parameters:
See also
scikitplot.corpus.pipeline.CorpusPipelineIntegrates this engine.
scikitplot.corpus._embeddings._multimodal_embedding.MultimodalEmbeddingEngineExtends 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 athreading.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 acustom_fn_id; without one, two different functions would share a key.Provenance:
embed_documentsstamps every document with the fingerprint ofembedding_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 inRetrievalIndexwill 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
backendvalues.For image/audio/video embeddings use
MultimodalEmbeddingEnginewhich supports"clip","whisper","wav2vec"in addition.
- cache_policy: CachePolicy | None = None#
- embed(texts)[source]#
Compute embeddings for
textswithout 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 dtypeself.dtype.
- Raises:
- ValueError
If
textsis empty.- ImportError
If the required backend library is not installed.
- Parameters:
- 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);statusis aCacheStatus.
- Raises:
- ValueError
If
textsis empty.
- Parameters:
- Return type:
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 withCachePolicy(unpinned= "resolve")), a custom provider’scustom_fn_id, the statedmodel_revisionof 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 asSTORE_FAILED, never raised.Developer. A hit refreshes the entry’s modification time; after a store,
enforce_boundsevicts 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
CorpusDocumentinstances in-place (setsdoc.embeddingon each).- Parameters:
- documentslist of CorpusDocument
Documents to embed. Each must have a non-empty
textfield.- input_pathpathlib.Path or None, optional
Source of the documents, for diagnostics only. Caching follows
enable_cacheandcache_policy(seeembed_cached); the key is content-addressed.
- Returns:
- list of CorpusDocument
The same list with
embeddingandembedding_manifest_idpopulated (viareplace()— originals are not mutated).
- Parameters:
- Return type:
Notes
Developer.
embedding_manifest_idis 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 overtextsand 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
Trueif the result was loaded from disk cache.
- Raises:
- ValueError
If
textsis empty.
- Parameters:
- Return type:
See also
embed_cachedThe 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
provideris the backend;modelthe model name, or for a custom provider itscustom_fn_id;revisionthe pinned revision orNone; plus dimension, dtype and normalisation.
- Raises:
- ValueError
If
dimensionis not a positive integer.
- Parameters:
dimension (int)
- Return type:
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.
Gallery examples#
Write Your Own Corpus Components: a Hamlet Walkthrough