File size: 1,406 Bytes
04f192c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | # SPDX-FileCopyrightText: Copyright contributors to the CopilotJ project.
#
# SPDX-License-Identifier: Apache-2.0
import logging
from langchain_core.embeddings import Embeddings
logger = logging.getLogger(__name__)
RAG_EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
_embeddings: Embeddings | None = None
__all__ = [
"RAG_EMBEDDING_MODEL",
"get_embeddings",
"new_local_embeddings",
]
def new_local_embeddings() -> Embeddings:
"""Create the local embedding model used by the bundled FAISS index."""
from langchain_huggingface import HuggingFaceEmbeddings
device = _detect_embedding_device()
logger.info("Loading local embedding model: %s on device: %s", RAG_EMBEDDING_MODEL, device)
return HuggingFaceEmbeddings(
model_name=RAG_EMBEDDING_MODEL,
model_kwargs={"device": device},
encode_kwargs={"normalize_embeddings": True},
)
def get_embeddings() -> Embeddings:
"""Get the local embeddings used for ImageJ RAG."""
global _embeddings
if _embeddings is None:
_embeddings = new_local_embeddings()
return _embeddings
def _detect_embedding_device() -> str:
try:
import torch
except ImportError:
return "cpu"
if torch.cuda.is_available():
return "cuda"
if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
return "mps"
return "cpu"
|