luciagomez commited on
Commit
3eeef5e
·
verified ·
1 Parent(s): 0ba1ae3

update retriever to add inference option

Browse files
Files changed (1) hide show
  1. retriever.py +85 -51
retriever.py CHANGED
@@ -1,35 +1,64 @@
1
- from huggingface_hub import hf_hub_download
2
  from FlagEmbedding import FlagICLModel
3
  import pandas as pd
4
  import faiss
5
  import numpy as np
 
 
6
 
7
- class FoundationRetriever:
8
- """
9
- Retrieve foundations whose missions align with a user perspective.
10
- Uses FAISS for efficient similarity search and BGE-en-ICL for encoding queries with examples.
11
- """
12
-
13
- def __init__(self, repo_id, parquet_file, faiss_file, use_fp16=False):
14
- """
15
- repo_id: Hugging Face dataset repo containing Parquet and FAISS index
16
- parquet_file: Parquet filename in repo
17
- faiss_file: FAISS index filename in repo
18
- use_fp16: whether to use FP16 for model inference
19
- """
20
- # Download files from Hugging Face
21
- parquet_path = hf_hub_download(repo_id, parquet_file)
22
- faiss_path = hf_hub_download(repo_id, faiss_file)
23
-
24
- # Load foundations dataframe
25
- self.df = pd.read_parquet(parquet_path)
26
-
27
- # Load FAISS index
28
- self.index = faiss.read_index(faiss_path)
29
- self.dim = self.index.d
30
-
31
- # Define few-shot examples for ICL query embedding
32
- examples_for_task = [
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  {
34
  "instruct": "Retrieve foundations whose mission aligns with the given perspective.",
35
  "query": "Protect marine life while educating children about ocean conservation",
@@ -42,27 +71,32 @@ class FoundationRetriever:
42
  }
43
  ]
44
 
45
- # Load BGE-en-ICL model
46
- self.model = FlagICLModel(
47
- "BAAI/bge-en-icl",
48
- query_instruction_for_retrieval="Given a user perspective about philanthropy, retrieve relevant foundation missions.",
49
- examples_for_task=examples_for_task,
50
- use_fp16=use_fp16
51
- )
52
-
53
- def find_aligned_foundations(self, perspective_text, top_k=5):
54
- """
55
- Returns a DataFrame with top-k foundations aligned with the user's perspective.
56
- """
57
- # Encode user perspective with ICL
58
- query_emb = self.model.encode_queries([perspective_text]).astype("float32")
59
- faiss.normalize_L2(query_emb)
60
-
61
- # Search FAISS
62
- distances, indices = self.index.search(query_emb, top_k)
63
-
64
- # Retrieve foundation info
65
- results = self.df.iloc[indices[0]][["Title", "Purpose"]].copy()
66
- results["similarity"] = distances[0]
67
-
68
- return results
 
 
 
 
 
 
1
+ from huggingface_hub import hf_hub_download, InferenceClient
2
  from FlagEmbedding import FlagICLModel
3
  import pandas as pd
4
  import faiss
5
  import numpy as np
6
+ import os
7
+ import json
8
 
9
+ # Define HF tokens
10
+ HF_TOKEN_read = os.environ.get("HF_TOKEN_read")
11
+ HF_TOKEN_inference = os.environ.get("HF_TOKEN_inf")
12
+
13
+ # Setup InferenceClient for embeddings
14
+ client = InferenceClient(provider="nebius", api_key=HF_TOKEN_inference)
15
+
16
+ # Dataset repo (private)
17
+ DATASET_REPO = "luciagomez/MrPhil_vector"
18
+
19
+ # -------------------------------------------------------------------
20
+ # 1. Download files from Hugging Face dataset
21
+ # -------------------------------------------------------------------
22
+ parquet_path = hf_hub_download(
23
+ repo_id=DATASET_REPO,
24
+ filename="foundations.parquet",
25
+ repo_type="dataset",
26
+ token=HF_TOKEN_read
27
+ )
28
+
29
+ faiss_path = hf_hub_download(
30
+ repo_id=DATASET_REPO,
31
+ filename="faiss.index",
32
+ repo_type="dataset",
33
+ token=HF_TOKEN_read
34
+ )
35
+
36
+ meta_path = hf_hub_download(
37
+ repo_id=DATASET_REPO,
38
+ filename="meta.json",
39
+ repo_type="dataset",
40
+ token=HF_TOKEN_read
41
+ )
42
+
43
+
44
+ # -------------------------------------------------------------------
45
+ # 2. Load data
46
+ # -------------------------------------------------------------------
47
+ df = pd.read_parquet(parquet_path)
48
+ index = faiss.read_index(faiss_path)
49
+ with open(meta_path, "r") as f:
50
+ meta = json.load(f)
51
+
52
+ dim = meta.get("embedding_dim", None)
53
+ n = meta.get("num_vectors", len(df))
54
+
55
+ print(f"Loaded FAISS index with {n} vectors of dimension {dim}")
56
+
57
+
58
+ # -------------------------------------------------------------------
59
+ # 3. Initialize BGE-ICL model for queries
60
+ # -------------------------------------------------------------------
61
+ examples = [
62
  {
63
  "instruct": "Retrieve foundations whose mission aligns with the given perspective.",
64
  "query": "Protect marine life while educating children about ocean conservation",
 
71
  }
72
  ]
73
 
74
+
75
+ #model = FlagICLModel(
76
+ # "BAAI/bge-en-icl",
77
+ # query_instruction_for_retrieval="Given a mission statement, retrieve foundations with aligned purposes.",
78
+ # examples_for_task=examples,
79
+ # use_fp16=False
80
+ #)
81
+
82
+ def encode_query(perspective):
83
+ payload = {"model": "BAAI/bge-en-icl",
84
+ "inputs": perspective,
85
+ "parameters": {"instruction": "Retrieve foundations aligned with perspective.",
86
+ "examples": examples}}
87
+ response = client.feature_extraction(**payload)
88
+ return np.array(response)
89
+
90
+ # -------------------------------------------------------------------
91
+ # 4. Retrieval function
92
+ # -------------------------------------------------------------------
93
+ def find_similar_foundations(perspective, top_k=5):
94
+ q_emb = encode_query(perspective).astype("float32")
95
+ faiss.normalize_L2(q_emb)
96
+ scores, idxs = index.search(q_emb, top_k)
97
+ return [
98
+ {"title": df.iloc[i]["Title"], "purpose": df.iloc[i]["Purpose"], "similarity": float(scores[0][j])}
99
+ for j, i in enumerate(idxs[0])
100
+ ]
101
+
102
+