Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

Move imports to be local

Karim Elmaaroufi33d1008f231e
diff --git a/dspy/retrieve/pinecone_rm.py b/dspy/retrieve/pinecone_rm.py
index fd888a178..92cf7005e 100644
--- a/dspy/retrieve/pinecone_rm.py
+++ b/dspy/retrieve/pinecone_rm.py
@@ -3,9 +3,7 @@ Retriever model for Pinecone
Author: Dhar Rawal (@drawal1)
"""
-import torch
from dsp.utils import dotdict
-from transformers import AutoTokenizer, AutoModel
from typing import Optional, List, Union
import openai
import dspy
@@ -68,6 +66,14 @@ class PineconeRM(dspy.Retrieve):
k: int = 3,
):
if local_embed_model is not None:
+ try:
+ import torch
+ from transformers import AutoModel, AutoTokenizer
+ except ImportError as exc:
+ raise ModuleNotFoundError(
+ "You need to install Hugging Face transformers library to use a local embedding model with PineconeRM."
+ ) from exc
+
self._local_embed_model = AutoModel.from_pretrained(local_embed_model)
self._local_tokenizer = AutoTokenizer.from_pretrained(local_embed_model)
self.use_local_model = True
@@ -142,9 +148,16 @@ class PineconeRM(dspy.Retrieve):
def _mean_pooling(
self,
- model_output: torch.tensor,
- attention_mask: torch.tensor
- ) -> torch.tensor:
+ model_output,
+ attention_mask
+ ):
+ try:
+ import torch
+ except ImportError as exc:
+ raise ModuleNotFoundError(
+ "You need to install torch to use a local embedding model with PineconeRM."
+ ) from exc
+
token_embeddings = model_output[0] # First element of model_output contains all token embeddings
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
@@ -166,6 +179,13 @@ class PineconeRM(dspy.Retrieve):
Returns:
List[List[float]]: List of embeddings corresponding to each query.
"""
+ try:
+ import torch
+ except ImportError as exc:
+ raise ModuleNotFoundError(
+ "You need to install torch to use a local embedding model with PineconeRM."
+ ) from exc
+
if not self.use_local_model:
embedding = openai.Embedding.create(
input=queries, model=self._openai_embed_model