suanan commited on
Commit
afbf115
1 Parent(s): 5f03843

v1.1 only cbg search index

Browse files
Files changed (1) hide show
  1. app.py +152 -152
app.py CHANGED
@@ -1,152 +1,152 @@
1
- import time
2
- import gradio as gr
3
- from datasets import load_dataset
4
- import pandas as pd
5
- from sentence_transformers import SentenceTransformer
6
- from sentence_transformers.quantization import quantize_embeddings
7
- import faiss
8
- from usearch.index import Index
9
- import datetime
10
-
11
-
12
- # Load titles and texts
13
- title_text_dataset = load_dataset("suanan/BP_POC", split="train", num_proc=4).select_columns(["url", "title", "text"])
14
-
15
- # Load the int8 and binary indices. Int8 is loaded as a view to save memory, as we never actually perform search with it.
16
- int8_view = Index.restore("index/BP_int8_usearch_1m.index", view=True)
17
- binary_index: faiss.IndexBinaryFlat = faiss.read_index_binary("index/BP_ubinary_faiss_1m.index")
18
- # binary_ivf: faiss.IndexBinaryIVF = faiss.read_index_binary("BP_ubinary_ivf_faiss_50m.index")
19
-
20
- # Load the SentenceTransformer model for embedding the queries
21
- model = SentenceTransformer(
22
- "BAAI/bge-m3",
23
- prompts={
24
- "retrieval": "Represent this sentence for searching relevant passages: ",
25
- },
26
- default_prompt_name="retrieval",
27
- )
28
-
29
-
30
- def search(query, top_k: int = 100, rescore_multiplier: int = 1, use_approx: bool = False):
31
- # 獲取當前時間
32
- now = datetime.datetime.now()
33
- print(f"當前時間: {now}, 問題: {query}")
34
- # 1. Embed the query as float32
35
- start_time = time.time()
36
- query_embedding = model.encode(query)
37
- embed_time = time.time() - start_time
38
-
39
- # 2. Quantize the query to ubinary
40
- start_time = time.time()
41
- query_embedding_ubinary = quantize_embeddings(query_embedding.reshape(1, -1), "ubinary")
42
- quantize_time = time.time() - start_time
43
-
44
- # 3. Search the binary index (either exact or approximate)
45
- # index = binary_ivf if use_approx else binary_index
46
- index = binary_index
47
- start_time = time.time()
48
- _scores, binary_ids = index.search(query_embedding_ubinary, top_k * rescore_multiplier)
49
- binary_ids = binary_ids[0]
50
- search_time = time.time() - start_time
51
-
52
- # 4. Load the corresponding int8 embeddings
53
- start_time = time.time()
54
- int8_embeddings = int8_view[binary_ids].astype(int)
55
- load_time = time.time() - start_time
56
-
57
- # 5. Rescore the top_k * rescore_multiplier using the float32 query embedding and the int8 document embeddings
58
- start_time = time.time()
59
- scores = query_embedding @ int8_embeddings.T
60
- rescore_time = time.time() - start_time
61
-
62
- # 6. Sort the scores and return the top_k
63
- start_time = time.time()
64
- indices = scores.argsort()[::-1][:top_k]
65
- top_k_indices = binary_ids[indices]
66
- top_k_scores = scores[indices]
67
- top_k_urls, top_k_titles, top_k_texts = zip(
68
- *[(title_text_dataset[idx]["url"], title_text_dataset[idx]["title"], title_text_dataset[idx]["text"]) for idx in top_k_indices.tolist()]
69
- )
70
- df = pd.DataFrame(
71
- {"Score": [round(value, 2) for value in top_k_scores], "Url": top_k_urls, "Title": top_k_titles, "Text": top_k_texts}
72
- )
73
- sort_time = time.time() - start_time
74
-
75
- return df, {
76
- "Embed Time": f"{embed_time:.4f} s",
77
- "Quantize Time": f"{quantize_time:.4f} s",
78
- "Search Time": f"{search_time:.4f} s",
79
- "Load Time": f"{load_time:.4f} s",
80
- "Rescore Time": f"{rescore_time:.4f} s",
81
- "Sort Time": f"{sort_time:.4f} s",
82
- "Total search Time": f"{quantize_time + search_time + load_time + rescore_time + sort_time:.4f} s",
83
- }
84
- def update_info(value):
85
- return f"{value}筆顯示出來"
86
-
87
- with gr.Blocks(title="") as demo:
88
- gr.Markdown(
89
- """
90
- ## 官網 Dataset & opensource model BAAI/bge-m3
91
- ### v1 測試POC
92
-
93
-
94
- Details:
95
- 1. 中文搜尋ok,英文像是:iphone 15,embedding的時候沒有轉成小寫,需要 寫成iPhone才可以準確搜尋到
96
- 2. 環境資源: python 3.10, linux: ubuntu 22.04, only cpu, ram max:7.7GB min:4.5GB 使用以上資源
97
- 3.
98
-
99
- 建立步驟:
100
- 1. excel 轉成 [dataset](https://huggingface.co/datasets/suanan/BP_POC), 花費約10秒內
101
- 2. dataset 內 轉成 title & text 做 embedding,以後可以新增keyword來加強搜尋出來的結果排序往前
102
- 3. 之後透過 Quantized Retrieval - Binary Search solution進行搜尋
103
-
104
-
105
- """
106
- )
107
- with gr.Row():
108
- with gr.Column(scale=75):
109
- query = gr.Textbox(
110
- label="官網 Dataset & opensource model BAAI/bge-m3, v1 測試POC",
111
- placeholder="輸入搜尋關鍵字或問句",
112
- )
113
- with gr.Column(scale=25):
114
- use_approx = gr.Radio(
115
- choices=[("精確搜尋", False), ("相關搜尋", True)],
116
- value=False,
117
- label="搜尋方法",
118
- )
119
-
120
- with gr.Row():
121
- with gr.Column(scale=2):
122
- top_k = gr.Slider(
123
- minimum=10,
124
- maximum=1000,
125
- step=5,
126
- value=100,
127
- label="顯示搜尋前幾筆",
128
- )
129
- info_text = gr.Textbox(value=update_info(top_k.value), interactive=False)
130
- with gr.Column(scale=2):
131
- rescore_multiplier = gr.Slider(
132
- minimum=1,
133
- maximum=10,
134
- step=1,
135
- value=1,
136
- label="Rescore multiplier",
137
- info="Search for `rescore_multiplier` as many documents to rescore",
138
- )
139
-
140
- search_button = gr.Button(value="Search")
141
-
142
- with gr.Row():
143
- with gr.Column(scale=4):
144
- output = gr.Dataframe(headers=["Score", "Title", "Text"])
145
- with gr.Column(scale=1):
146
- json = gr.JSON()
147
- top_k.change(fn=update_info, inputs=top_k, outputs=info_text)
148
- query.submit(search, inputs=[query, top_k, rescore_multiplier, use_approx], outputs=[output, json])
149
- search_button.click(search, inputs=[query, top_k, rescore_multiplier, use_approx], outputs=[output, json])
150
-
151
- demo.queue()
152
- demo.launch(share=True)
 
1
+ import time
2
+ import gradio as gr
3
+ from datasets import load_dataset
4
+ import pandas as pd
5
+ from sentence_transformers import SentenceTransformer
6
+ from sentence_transformers.quantization import quantize_embeddings
7
+ import faiss
8
+ from usearch.index import Index
9
+ import datetime
10
+
11
+
12
+ # Load titles and texts
13
+ title_text_dataset = load_dataset("suanan/BP_POC", split="train", num_proc=4).select_columns(["url", "title", "text"])
14
+
15
+ # Load the int8 and binary indices. Int8 is loaded as a view to save memory, as we never actually perform search with it.
16
+ int8_view = Index.restore("index/BP_CBG_int8_usearch_1m.index", view=True)
17
+ binary_index: faiss.IndexBinaryFlat = faiss.read_index_binary("index/BP_CBG_ubinary_faiss_1m.index")
18
+ # binary_ivf: faiss.IndexBinaryIVF = faiss.read_index_binary("BP_ubinary_ivf_faiss_50m.index")
19
+
20
+ # Load the SentenceTransformer model for embedding the queries
21
+ model = SentenceTransformer(
22
+ "BAAI/bge-m3",
23
+ prompts={
24
+ "retrieval": "Represent this sentence for searching relevant passages: ",
25
+ },
26
+ default_prompt_name="retrieval",
27
+ )
28
+
29
+
30
+ def search(query, top_k: int = 100, rescore_multiplier: int = 1, use_approx: bool = False):
31
+ # 獲取當前時間
32
+ now = datetime.datetime.now()
33
+ print(f"當前時間: {now}, 問題: {query}")
34
+ # 1. Embed the query as float32
35
+ start_time = time.time()
36
+ query_embedding = model.encode(query)
37
+ embed_time = time.time() - start_time
38
+
39
+ # 2. Quantize the query to ubinary
40
+ start_time = time.time()
41
+ query_embedding_ubinary = quantize_embeddings(query_embedding.reshape(1, -1), "ubinary")
42
+ quantize_time = time.time() - start_time
43
+
44
+ # 3. Search the binary index (either exact or approximate)
45
+ # index = binary_ivf if use_approx else binary_index
46
+ index = binary_index
47
+ start_time = time.time()
48
+ _scores, binary_ids = index.search(query_embedding_ubinary, top_k * rescore_multiplier)
49
+ binary_ids = binary_ids[0]
50
+ search_time = time.time() - start_time
51
+
52
+ # 4. Load the corresponding int8 embeddings
53
+ start_time = time.time()
54
+ int8_embeddings = int8_view[binary_ids].astype(int)
55
+ load_time = time.time() - start_time
56
+
57
+ # 5. Rescore the top_k * rescore_multiplier using the float32 query embedding and the int8 document embeddings
58
+ start_time = time.time()
59
+ scores = query_embedding @ int8_embeddings.T
60
+ rescore_time = time.time() - start_time
61
+
62
+ # 6. Sort the scores and return the top_k
63
+ start_time = time.time()
64
+ indices = scores.argsort()[::-1][:top_k]
65
+ top_k_indices = binary_ids[indices]
66
+ top_k_scores = scores[indices]
67
+ top_k_urls, top_k_titles, top_k_texts = zip(
68
+ *[(title_text_dataset[idx]["url"], title_text_dataset[idx]["title"], title_text_dataset[idx]["text"]) for idx in top_k_indices.tolist()]
69
+ )
70
+ df = pd.DataFrame(
71
+ {"Score": [round(value, 2) for value in top_k_scores], "Url": top_k_urls, "Title": top_k_titles, "Text": top_k_texts}
72
+ )
73
+ sort_time = time.time() - start_time
74
+
75
+ return df, {
76
+ "Embed Time": f"{embed_time:.4f} s",
77
+ "Quantize Time": f"{quantize_time:.4f} s",
78
+ "Search Time": f"{search_time:.4f} s",
79
+ "Load Time": f"{load_time:.4f} s",
80
+ "Rescore Time": f"{rescore_time:.4f} s",
81
+ "Sort Time": f"{sort_time:.4f} s",
82
+ "Total search Time": f"{quantize_time + search_time + load_time + rescore_time + sort_time:.4f} s",
83
+ }
84
+ def update_info(value):
85
+ return f"{value}筆顯示出來"
86
+
87
+ with gr.Blocks(title="") as demo:
88
+ gr.Markdown(
89
+ """
90
+ ## 官網 Dataset & opensource model BAAI/bge-m3
91
+ ### v1 測試POC
92
+
93
+
94
+ Details:
95
+ 1. 中文搜尋ok,英文像是:iphone 15,embedding的時候沒有轉成小寫,需要 寫成iPhone才可以準確搜尋到
96
+ 2. 環境資源: python 3.10, linux: ubuntu 22.04, only cpu, ram max:7.7GB min:4.5GB 使用以上資源
97
+ 3.
98
+
99
+ 建立步驟:
100
+ 1. excel 轉成 [dataset](https://huggingface.co/datasets/suanan/BP_POC), 花費約10秒內
101
+ 2. dataset 內 轉成 title & text 做 embedding,以後可以新增keyword來加強搜��出來的結果排序往前
102
+ 3. 之後透過 Quantized Retrieval - Binary Search solution進行搜尋
103
+
104
+
105
+ """
106
+ )
107
+ with gr.Row():
108
+ with gr.Column(scale=75):
109
+ query = gr.Textbox(
110
+ label="官網 Dataset & opensource model BAAI/bge-m3, v1 測試POC",
111
+ placeholder="輸入搜尋關鍵字或問句",
112
+ )
113
+ with gr.Column(scale=25):
114
+ use_approx = gr.Radio(
115
+ choices=[("精確搜尋", False), ("相關搜尋", True)],
116
+ value=False,
117
+ label="搜尋方法",
118
+ )
119
+
120
+ with gr.Row():
121
+ with gr.Column(scale=2):
122
+ top_k = gr.Slider(
123
+ minimum=10,
124
+ maximum=1000,
125
+ step=5,
126
+ value=100,
127
+ label="顯示搜尋前幾筆",
128
+ )
129
+ info_text = gr.Textbox(value=update_info(top_k.value), interactive=False)
130
+ with gr.Column(scale=2):
131
+ rescore_multiplier = gr.Slider(
132
+ minimum=1,
133
+ maximum=10,
134
+ step=1,
135
+ value=1,
136
+ label="Rescore multiplier",
137
+ info="Search for `rescore_multiplier` as many documents to rescore",
138
+ )
139
+
140
+ search_button = gr.Button(value="Search")
141
+
142
+ with gr.Row():
143
+ with gr.Column(scale=4):
144
+ output = gr.Dataframe(headers=["Score", "Title", "Text"])
145
+ with gr.Column(scale=1):
146
+ json = gr.JSON()
147
+ top_k.change(fn=update_info, inputs=top_k, outputs=info_text)
148
+ query.submit(search, inputs=[query, top_k, rescore_multiplier, use_approx], outputs=[output, json])
149
+ search_button.click(search, inputs=[query, top_k, rescore_multiplier, use_approx], outputs=[output, json])
150
+
151
+ demo.queue()
152
+ demo.launch(share=True)