louisbrulenaudet commited on
Commit
6b2dcd4
1 Parent(s): 0aa46ed

Upload 11 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ faiss_ubinary.index filter=lfs diff=lfs merge=lfs -text
37
+ usearch_int8.index filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md CHANGED
@@ -1,13 +1,61 @@
1
  ---
2
- title: Legalkit Retrieval
3
- emoji: 📊
4
- colorFrom: red
5
- colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 4.25.0
8
  app_file: app.py
9
- pinned: false
10
  license: apache-2.0
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: LegalKit Retrieval
3
+ emoji: 📖
4
+ colorFrom: blue
5
+ colorTo: purple
6
  sdk: gradio
7
  sdk_version: 4.25.0
8
  app_file: app.py
9
+ pinned: true
10
  license: apache-2.0
11
+ short_description: A binary Search with Scalar Rescoring through legal codes
12
  ---
13
 
14
+ # LegalKit Retrieval, a binary Search with Scalar (int8) Rescoring through French legal codes
15
+
16
+ This space showcases the [tsdae-lemone-mbert-base](https://huggingface.co/louisbrulenaudet/tsdae-lemone-mbert-base)
17
+ model by Louis Brulé Naudet, a sentence embedding model based on BERT fitted using Transformer-based Sequential Denoising Auto-Encoder for unsupervised sentence embedding learning with one objective : french legal domain adaptation.
18
+
19
+ This process is designed to be memory efficient and fast, with the binary index being small enough to fit in memory and the int8 index being loaded as a view to save memory.
20
+ In total, this process requires keeping 1) the model in memory, 2) the binary index in memory, and 3) the int8 index on disk.
21
+
22
+ Additionally, the binary index is much faster (up to 32x) to search than the float32 index, while the rescoring is also extremely efficient. In conclusion, this process allows for fast, scalable, cheap, and memory-efficient retrieval.
23
+
24
+ Notes:
25
+ - The SentenceTransformer model currently in use is in beta and may not be suitable for direct use in production.
26
+
27
+ ## Dependencies
28
+ ### Libraries Used:
29
+
30
+ - **Accelerate** (v0.29.1): A Python library for high-performance computing, enabling faster execution of computational tasks.
31
+ - **Faiss-GPU** (v1.7.2): A GPU-accelerated library for efficient similarity search and clustering of dense vectors, essential for high-dimensional data analysis.
32
+ - **Gradio** (v4.25.0): An intuitive library for creating customizable UI components around machine learning models, simplifying model deployment and interaction.
33
+ - **Polars** (v0.20.18): A blazing-fast DataFrame library for Rust, providing efficient data manipulation capabilities for large datasets.
34
+ - **Sentence-Transformers** (v2.6.1): A versatile library for generating sentence embeddings, facilitating various natural language processing tasks such as semantic similarity and text classification.
35
+ - **Spaces** (v0.25.0): A utility library designed to optimize GPU resource management, enhancing efficiency and scalability in GPU-based computing environments.
36
+ - **Usearch** (v2.10.5): A powerful library for performing fast approximate nearest neighbor search, crucial for tasks like recommendation systems and data clustering.
37
+
38
+ ### Installation Guide
39
+
40
+ To install all the dependencies, you can use the following command:
41
+
42
+ ```shell
43
+ pip3 install accelerate faiss-gpu gradio polars sentence-transformers spaces usearch
44
+ ```
45
+
46
+ Note: Ensure you have Python installed on your system before proceeding with the installation of these libraries.
47
+
48
+ ## Citing this project
49
+ If you use this code in your research, please use the following BibTeX entry.
50
+
51
+ ```BibTeX
52
+ @misc{louisbrulenaudet2024,
53
+ author = {Louis Brulé Naudet},
54
+ title = {LegalKit Retrieval, a binary Search with Scalar (int8) Rescoring through French legal codes},
55
+ howpublished = {\url{https://huggingface.co/spaces/louisbrulenaudet/legalkit-retrieval}},
56
+ year = {2024}
57
+ }
58
+
59
+ ```
60
+ ## Feedback
61
+ If you have any feedback, please reach out at [louisbrulenaudet@icloud.com](mailto:louisbrulenaudet@icloud.com).
app.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) Louis Brulé Naudet. All Rights Reserved.
3
+ # This software may be used and distributed according to the terms of the License Agreement.
4
+ #
5
+ # Unless required by applicable law or agreed to in writing, software
6
+ # distributed under the License is distributed on an "AS IS" BASIS,
7
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8
+ # See the License for the specific language governing permissions and
9
+ # limitations under the License.
10
+
11
+ import gradio as gr
12
+ import polars as pl
13
+ import spaces
14
+ import torch
15
+
16
+ from typing import Tuple, List, Union
17
+
18
+ from dataset import Dataset
19
+ from similarity_search import SimilaritySearch
20
+
21
+
22
+ def setup(
23
+ description: str,
24
+ model_name: str,
25
+ device: str,
26
+ ndim: int,
27
+ metric: str,
28
+ dtype: str
29
+ ) -> Tuple:
30
+ """
31
+ Set up the model and tokenizer for a given pre-trained model ID.
32
+
33
+ Parameters
34
+ ----------
35
+ description : str
36
+ A string containing additional description information.
37
+
38
+ model_name : str
39
+ Name of the pre-trained model to load.
40
+
41
+ device : str
42
+ Device to run the model on, e.g., 'cuda' or 'cpu'.
43
+
44
+ ndim : int
45
+ Dimensionality of the model.
46
+
47
+ metric : str
48
+ Metric for similarity search.
49
+
50
+ dtype : str
51
+ Data type of the model.
52
+
53
+ Returns
54
+ -------
55
+ instance : SimilaritySearch
56
+ A class dedicated to encoding text data, quantizing embeddings, and managing indices for efficient similarity search.
57
+
58
+ dataset : datasets.Dataset
59
+ The loaded dataset.
60
+
61
+ dataframe: pl.DataFrame
62
+ A Polars DataFrame representing the dataset.
63
+
64
+ description : str
65
+ A string containing additional description information.
66
+ """
67
+ try:
68
+ if not torch.cuda.is_available():
69
+ description += "\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>"
70
+
71
+ instance = SimilaritySearch(
72
+ model_name=model_name,
73
+ device=device,
74
+ ndim=ndim,
75
+ metric=metric,
76
+ dtype=dtype
77
+ )
78
+
79
+ instance.load_usearch_index_view(
80
+ index_path="./usearch_int8.index",
81
+ )
82
+
83
+ instance.load_faiss_index(
84
+ index_path="./faiss_ubinary.index",
85
+ )
86
+
87
+ dataset = Dataset.load(
88
+ dataset_path="./legalkit.hf"
89
+ )
90
+
91
+ dataframe = Dataset.convert_to_polars(
92
+ dataset=dataset
93
+ )
94
+
95
+ return instance, dataset, dataframe, description
96
+
97
+ except Exception as e:
98
+ error_message = f"An error occurred during setup: {str(e)}"
99
+ raise RuntimeError(error_message) from e
100
+
101
+
102
+ DESCRIPTION = """\
103
+ # LegalKit Retrieval, a binary Search with Scalar (int8) Rescoring through French legal codes
104
+
105
+ This space showcases the [tsdae-lemone-mbert-base](https://huggingface.co/louisbrulenaudet/tsdae-lemone-mbert-base)
106
+ model by Louis Brulé Naudet, a sentence embedding model based on BERT fitted using Transformer-based Sequential Denoising Auto-Encoder for unsupervised sentence embedding learning with one objective : french legal domain adaptation.
107
+
108
+ This process is designed to be memory efficient and fast, with the binary index being small enough to fit in memory and the int8 index being loaded as a view to save memory.
109
+ Additionally, the binary index is much faster (up to 32x) to search than the float32 index, while the rescoring is also extremely efficient.
110
+ """
111
+
112
+ instance, dataset, dataframe, DESCRIPTION = setup(
113
+ model_name="louisbrulenaudet/tsdae-lemone-mbert-base",
114
+ description=DESCRIPTION,
115
+ device="cuda",
116
+ ndim=768,
117
+ metric="ip",
118
+ dtype="i8"
119
+ )
120
+
121
+
122
+ @spaces.GPU
123
+ def search(
124
+ query:str,
125
+ top_k:int,
126
+ rescore_multiplier:int
127
+ ) -> any:
128
+ """
129
+ Perform a search operation using the initialized GPU space.
130
+
131
+ Parameters
132
+ ----------
133
+ query : str
134
+ The query for which similarity search is performed.
135
+
136
+ top_k : int
137
+ The number of top results to return.
138
+
139
+ rescore_multiplier : int
140
+ A multiplier for rescore operation.
141
+
142
+ Returns
143
+ -------
144
+ any
145
+ The search results in a suitable format.
146
+
147
+ Notes
148
+ -----
149
+ This function performs a search operation using the initialized GPU space
150
+ and returns the search results in a format compatible with the provided
151
+ space.
152
+
153
+ Examples
154
+ --------
155
+ >>> results = search(query="example query", top_k=10, rescore_multiplier=2)
156
+ """
157
+ global instance
158
+ global dataset
159
+ global dataframe
160
+
161
+ top_k_scores, top_k_indices = instance.search(
162
+ query=query,
163
+ top_k=top_k,
164
+ rescore_multiplier=rescore_multiplier
165
+ )
166
+
167
+ scores_df = pl.DataFrame(
168
+ {
169
+ "index": top_k_indices,
170
+ "score": top_k_scores
171
+ }
172
+ ).with_columns(
173
+ pl.col("index").cast(pl.UInt32)
174
+ )
175
+
176
+ results_df = dataframe.filter(
177
+ pl.col("index").is_in(top_k_indices)
178
+ ).join(
179
+ scores_df,
180
+ how="inner",
181
+ on="index"
182
+ ).sort(
183
+ by="score",
184
+ descending=True
185
+ ).select(
186
+ [
187
+ "score",
188
+ "input",
189
+ "output",
190
+ "start",
191
+ "expiration"
192
+ ]
193
+ )
194
+
195
+ return gr.Dataframe(
196
+ value=results_df,
197
+ type="polars",
198
+ render=True
199
+ )
200
+
201
+
202
+ with gr.Blocks(title="Quantized Retrieval") as demo:
203
+ gr.Markdown(
204
+ value=DESCRIPTION
205
+ )
206
+ gr.DuplicateButton()
207
+
208
+ with gr.Row():
209
+ with gr.Column():
210
+ query = gr.Textbox(
211
+ label="Query for French legal codes articles",
212
+ placeholder="Enter a query to search for relevant texts from the French law.",
213
+ )
214
+
215
+ with gr.Row():
216
+ with gr.Column(scale=2):
217
+ top_k = gr.Slider(
218
+ minimum=1,
219
+ maximum=100,
220
+ step=1,
221
+ value=20,
222
+ label="Number of documents to retrieve",
223
+ info="Number of documents to retrieve from the binary search.",
224
+ )
225
+ with gr.Column(scale=2):
226
+ rescore_multiplier = gr.Slider(
227
+ minimum=1,
228
+ maximum=10,
229
+ step=1,
230
+ value=4,
231
+ label="Rescore multiplier",
232
+ info="Search for 'rescore_multiplier' as many documents to rescore.",
233
+ )
234
+
235
+ search_button = gr.Button(value="Search")
236
+
237
+ with gr.Row():
238
+ with gr.Column():
239
+ output = gr.Dataframe(
240
+ render=False
241
+ )
242
+
243
+ query.submit(
244
+ search,
245
+ inputs=[
246
+ query,
247
+ top_k,
248
+ rescore_multiplier
249
+ ],
250
+ outputs=[
251
+ output
252
+ ]
253
+ )
254
+
255
+ search_button.click(
256
+ search,
257
+ inputs=[
258
+ query,
259
+ top_k,
260
+ rescore_multiplier
261
+ ],
262
+ outputs=[
263
+ output,
264
+ ]
265
+ )
266
+
267
+
268
+ if __name__ == "__main__":
269
+ demo.queue().launch(
270
+ show_api=False
271
+ )
dataset.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) Louis Brulé Naudet. All Rights Reserved.
3
+ # This software may be used and distributed according to the terms of the License Agreement.
4
+ #
5
+ # Unless required by applicable law or agreed to in writing, software
6
+ # distributed under the License is distributed on an "AS IS" BASIS,
7
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8
+ # See the License for the specific language governing permissions and
9
+ # limitations under the License.
10
+
11
+ import datasets
12
+ import polars as pl
13
+
14
+
15
+ class Dataset:
16
+ @staticmethod
17
+ def load(
18
+ dataset_path:str
19
+ ):
20
+ """
21
+ Load a dataset from disk.
22
+
23
+ Parameters
24
+ ----------
25
+ dataset_path : str
26
+ The path to the dataset on disk.
27
+
28
+ Returns
29
+ -------
30
+ datasets.Dataset
31
+ The loaded dataset.
32
+
33
+ Notes
34
+ -----
35
+ This method statically loads a dataset from disk using the `load_from_disk` function
36
+ provided by the `datasets` module. The dataset is expected to be stored in a specific
37
+ format supported by the `datasets` library.
38
+
39
+ Example
40
+ -------
41
+ >>> dataset_path = "/path/to/dataset"
42
+ >>> dataset = Dataset.load(dataset_path)
43
+ """
44
+ dataset = datasets.load_from_disk(
45
+ dataset_path=dataset_path
46
+ )
47
+
48
+ return dataset
49
+
50
+
51
+ @staticmethod
52
+ def save(
53
+ dataset: datasets.Dataset,
54
+ dataset_path: str
55
+ ) -> None:
56
+ """
57
+ Save a dataset to disk.
58
+
59
+ Parameters
60
+ ----------
61
+ dataset : datasets.Dataset
62
+ The dataset to be saved.
63
+
64
+ dataset_path : str
65
+ The path where the dataset will be saved on disk.
66
+
67
+ Returns
68
+ -------
69
+ None
70
+
71
+ Notes
72
+ -----
73
+ This method statically saves a dataset to disk using the `save_to_disk` function
74
+ provided by the `datasets` module. The dataset is expected to be in a format
75
+ supported by the `datasets` library.
76
+
77
+ Example
78
+ -------
79
+ >>> dataset = load_dataset("my_dataset")
80
+ >>> dataset_path = "/path/to/save/dataset"
81
+ >>> Dataset.save(dataset, dataset_path)
82
+ """
83
+ datasets.save_to_disk(
84
+ dataset,
85
+ dataset_path
86
+ )
87
+
88
+ return None
89
+
90
+ @staticmethod
91
+ def convert_to_polars(
92
+ dataset: datasets.Dataset
93
+ ) -> pl.DataFrame:
94
+ """
95
+ Convert a dataset to a Polars DataFrame.
96
+
97
+ Parameters
98
+ ----------
99
+ dataset : datasets.Dataset
100
+ The dataset to be converted to a Polars DataFrame.
101
+
102
+ Returns
103
+ -------
104
+ pl.DataFrame
105
+ A Polars DataFrame representing the dataset.
106
+
107
+ Notes
108
+ -----
109
+ This method converts a dataset object to a Polars DataFrame, which is a
110
+ memory-efficient and fast data manipulation library for Rust.
111
+
112
+ Raises
113
+ ------
114
+ Exception
115
+ If an error occurs during the conversion process.
116
+
117
+ Examples
118
+ --------
119
+ >>> dataset = datasets.Dataset(data=arrow_table)
120
+ >>> dataframe = ClassName.convert_to_polars(dataset)
121
+ """
122
+ try:
123
+ dataframe = pl.from_arrow(dataset.data.table).with_row_index()
124
+
125
+ except:
126
+ dataframe = pl.from_arrow(dataset.data.table).with_row_count(
127
+ name="index"
128
+ )
129
+
130
+ return dataframe
131
+
faiss_ubinary.index ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b7e8b15577db9edc73dcf8e2a23c500ffe0b87e15e5f70ede4f7fb4036acd344
3
+ size 15217569
legalkit.hf/data-00000-of-00001.arrow ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ac4b9fc03afc706ccff577b7740e559a21b8821ab8472b54eff549aef580c5bf
3
+ size 161264032
legalkit.hf/dataset_info.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "citation": "",
3
+ "description": "",
4
+ "features": {
5
+ "instruction": {
6
+ "dtype": "string",
7
+ "_type": "Value"
8
+ },
9
+ "input": {
10
+ "dtype": "string",
11
+ "_type": "Value"
12
+ },
13
+ "output": {
14
+ "dtype": "string",
15
+ "_type": "Value"
16
+ },
17
+ "start": {
18
+ "dtype": "string",
19
+ "_type": "Value"
20
+ },
21
+ "expiration": {
22
+ "dtype": "string",
23
+ "_type": "Value"
24
+ },
25
+ "num": {
26
+ "dtype": "string",
27
+ "_type": "Value"
28
+ }
29
+ },
30
+ "homepage": "",
31
+ "license": ""
32
+ }
legalkit.hf/state.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_data_files": [
3
+ {
4
+ "filename": "data-00000-of-00001.arrow"
5
+ }
6
+ ],
7
+ "_fingerprint": "aeae96a548e712fe",
8
+ "_format_columns": [
9
+ "instruction",
10
+ "input",
11
+ "output",
12
+ "start",
13
+ "expiration",
14
+ "num"
15
+ ],
16
+ "_format_kwargs": {},
17
+ "_format_type": null,
18
+ "_output_all_columns": false,
19
+ "_split": null
20
+ }
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ accelerate==0.29.1
2
+ faiss-gpu==1.7.2
3
+ gradio==4.25.0
4
+ polars==0.20.18
5
+ sentence-transformers==2.6.1
6
+ spaces==0.25.0
7
+ usearch==2.10.5
similarity_search.py ADDED
@@ -0,0 +1,539 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) Louis Brulé Naudet. All Rights Reserved.
3
+ # This software may be used and distributed according to the terms of the License Agreement.
4
+ #
5
+ # Unless required by applicable law or agreed to in writing, software
6
+ # distributed under the License is distributed on an "AS IS" BASIS,
7
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8
+ # See the License for the specific language governing permissions and
9
+ # limitations under the License.
10
+
11
+ import faiss
12
+ import numpy as np
13
+ import torch
14
+
15
+ from usearch.index import Index
16
+
17
+ from sentence_transformers import SentenceTransformer
18
+ from sentence_transformers.quantization import quantize_embeddings
19
+
20
+ from typing import Tuple, List, Union
21
+
22
+ class SimilaritySearch:
23
+ """
24
+ A class dedicated to encoding text data, quantizing embeddings, and managing indices for efficient similarity search.
25
+
26
+ Attributes
27
+ ----------
28
+ model_name : str
29
+ Name or identifier of the embedding model.
30
+
31
+ device : str
32
+ Computation device ('cpu' or 'cuda').
33
+
34
+ ndim : int
35
+ Dimension of the embeddings.
36
+
37
+ metric : str
38
+ Metric used for the index ('ip' for inner product, etc.).
39
+
40
+ dtype : str
41
+ Data type for the index ('i8' for int8, etc.).
42
+
43
+ Methods
44
+ -------
45
+ encode(corpus, normalize_embeddings=True)
46
+ Encodes a list of text data into embeddings.
47
+
48
+ quantize_embeddings(embeddings, quantization_type)
49
+ Quantizes the embeddings for efficient storage and search.
50
+
51
+ create_faiss_index(ubinary_embeddings, index_path)
52
+ Creates and saves a FAISS binary index.
53
+
54
+ create_usearch_index(int8_embeddings, index_path)
55
+ Creates and saves a USEARCH integer index.
56
+
57
+ load_usearch_index_view(index_path)
58
+ Loads a USEARCH index as a view for memory-efficient operations.
59
+
60
+ load_faiss_index(index_path)
61
+ Loads a FAISS binary index for searching.
62
+
63
+ search(query, top_k=10, rescore_multiplier=4)
64
+ Performs a search operation against the indexed embeddings.
65
+ """
66
+ def __init__(
67
+ self,
68
+ model_name: str,
69
+ device: str = "cuda",
70
+ ndim: int = 1024,
71
+ metric: str = "ip",
72
+ dtype: str = "i8"
73
+ ):
74
+ """
75
+ Initializes the EmbeddingIndexer with the specified model, device, and index configurations.
76
+
77
+ Parameters
78
+ ----------
79
+ model_name : str
80
+ The name or identifier of the SentenceTransformer model to use for embedding.
81
+
82
+ device : str, optional
83
+ The computation device to use ('cpu' or 'cuda'). Default is 'cuda'.
84
+
85
+ ndim : int, optional
86
+ The dimensionality of the embeddings. Default is 1024.
87
+
88
+ metric : str, optional
89
+ The metric used for the index ('ip' for inner product). Default is 'ip'.
90
+
91
+ dtype : str, optional
92
+ The data type for the USEARCH index ('i8' for 8-bit integer). Default is 'i8'.
93
+ """
94
+ self.model_name = model_name
95
+ self.device = device
96
+ self.ndim = ndim
97
+ self.metric = metric
98
+ self.dtype = dtype
99
+ self.model = SentenceTransformer(
100
+ self.model_name,
101
+ device=self.device
102
+ )
103
+
104
+ self.binary_index = None
105
+ self.int8_index = None
106
+
107
+
108
+ def encode(
109
+ self,
110
+ corpus: list,
111
+ normalize_embeddings: bool = True
112
+ ) -> np.ndarray:
113
+ """
114
+ Encodes the given corpus into full-precision embeddings.
115
+
116
+ Parameters
117
+ ----------
118
+ corpus : list
119
+ A list of sentences to be encoded.
120
+
121
+ normalize_embeddings : bool, optional
122
+ Whether to normalize returned vectors to have length 1. In that case,
123
+ the faster dot-product (util.dot_score) instead of cosine similarity can be used. Default is True.
124
+
125
+ Returns
126
+ -------
127
+ np.ndarray
128
+ The full-precision embeddings of the corpus.
129
+
130
+ Notes
131
+ -----
132
+ This method normalizes the embeddings and shows the progress bar during the encoding process.
133
+ """
134
+ try:
135
+ embeddings = self.model.encode(
136
+ corpus,
137
+ normalize_embeddings=normalize_embeddings,
138
+ show_progress_bar=True
139
+ )
140
+ return embeddings
141
+
142
+ except Exception as e:
143
+ print(f"An error occurred during encoding: {e}")
144
+
145
+
146
+ def quantize_embeddings(
147
+ self,
148
+ embeddings: np.ndarray,
149
+ quantization_type: str
150
+ ) -> Union[np.ndarray, bytearray]:
151
+ """
152
+ Quantizes the given embeddings based on the specified quantization type ('ubinary' or 'int8').
153
+
154
+ Parameters
155
+ ----------
156
+ embeddings : np.ndarray
157
+ The full-precision embeddings to be quantized.
158
+ quantization_type : str
159
+ The type of quantization ('ubinary' for unsigned binary, 'int8' for 8-bit integers).
160
+
161
+ Returns
162
+ -------
163
+ Union[np.ndarray, bytearray]
164
+ The quantized embeddings.
165
+
166
+ Raises
167
+ ------
168
+ ValueError
169
+ If an unsupported quantization type is provided.
170
+ """
171
+ try:
172
+ if quantization_type == "ubinary":
173
+ return self._quantize_to_ubinary(
174
+ embeddings=embeddings
175
+ )
176
+
177
+ elif quantization_type == "int8":
178
+ return self._quantize_to_int8(
179
+ embeddings=embeddings
180
+ )
181
+
182
+ else:
183
+ raise ValueError(f"Unsupported quantization type: {quantization_type}")
184
+
185
+ except Exception as e:
186
+ print(f"An error occurred during quantization: {e}")
187
+
188
+
189
+ def create_faiss_index(
190
+ self,
191
+ ubinary_embeddings: bytearray,
192
+ index_path: str = None,
193
+ save: bool = False
194
+ ) -> None:
195
+ """
196
+ Creates and saves a FAISS binary index from ubinary embeddings.
197
+
198
+ Parameters
199
+ ----------
200
+ ubinary_embeddings : bytearray
201
+ The ubinary-quantized embeddings.
202
+
203
+ index_path : str, optional
204
+ The file path to save the FAISS binary index. Default is None.
205
+
206
+ save : bool, optional
207
+ Indicator for saving the index. Default is False.
208
+
209
+ Notes
210
+ -----
211
+ The dimensionality of the index is specified during the class initialization (default is 1024).
212
+ """
213
+ try:
214
+ self.binary_index = faiss.IndexBinaryFlat(
215
+ self.ndim
216
+ )
217
+ self.binary_index.add(
218
+ ubinary_embeddings
219
+ )
220
+
221
+ if save and index_path:
222
+ self._save_faiss_index_binary(
223
+ index_path=index_path
224
+ )
225
+
226
+ except Exception as e:
227
+ print(f"An error occurred during index creation: {e}")
228
+
229
+
230
+ def create_usearch_index(
231
+ self,
232
+ int8_embeddings: np.ndarray,
233
+ index_path: str = None,
234
+ save: bool = False
235
+ ) -> None:
236
+ """
237
+ Creates and saves a USEARCH integer index from int8 embeddings.
238
+
239
+ Parameters
240
+ ----------
241
+ int8_embeddings : np.ndarray
242
+ The int8-quantized embeddings.
243
+
244
+ index_path : str, optional
245
+ The file path to save the USEARCH integer index. Default is None.
246
+
247
+ save : bool, optional
248
+ Indicator for saving the index. Default is False.
249
+
250
+ Returns
251
+ -------
252
+ None
253
+
254
+ Notes
255
+ -----
256
+ The dimensionality and metric of the index are specified during class initialization.
257
+ """
258
+ try:
259
+ self.int8_index = Index(
260
+ ndim=self.ndim,
261
+ metric=self.metric,
262
+ dtype=self.dtype
263
+ )
264
+
265
+ self.int8_index.add(
266
+ np.arange(
267
+ len(int8_embeddings)
268
+ ),
269
+ int8_embeddings
270
+ )
271
+
272
+ if save == True and index_path:
273
+ self._save_int8_index(
274
+ index_path=index_path
275
+ )
276
+
277
+ return self.int8_index
278
+
279
+ except Exception as e:
280
+ print(f"An error occurred during USEARCH index creation: {e}")
281
+
282
+
283
+ def load_usearch_index_view(
284
+ self,
285
+ index_path: str
286
+ ) -> any:
287
+ """
288
+ Loads a USEARCH index as a view for memory-efficient operations.
289
+
290
+ Parameters
291
+ ----------
292
+ index_path : str
293
+ The file path to the USEARCH index to be loaded as a view.
294
+
295
+ Returns
296
+ -------
297
+ object
298
+ A view of the USEARCH index for memory-efficient similarity search operations.
299
+
300
+ Notes
301
+ -----
302
+ Implementing this would depend on the specific USEARCH index handling library being used.
303
+ """
304
+ try:
305
+ self.int8_index = Index.restore(
306
+ index_path,
307
+ view=True
308
+ )
309
+
310
+ return self.int8_index
311
+
312
+ except Exception as e:
313
+ print(f"An error occurred while loading USEARCH index: {e}")
314
+
315
+
316
+ def load_faiss_index(
317
+ self,
318
+ index_path: str
319
+ ) -> None:
320
+ """
321
+ Loads a FAISS binary index from a specified file path.
322
+
323
+ This method loads a binary index created by FAISS into the class
324
+ attribute `binary_index`, ready for performing similarity searches.
325
+
326
+ Parameters
327
+ ----------
328
+ index_path : str
329
+ The file path to the saved FAISS binary index.
330
+
331
+ Returns
332
+ -------
333
+ None
334
+
335
+ Notes
336
+ -----
337
+ The loaded index is stored in the `binary_index` attribute of the class.
338
+ Ensure that the index at `index_path` is compatible with the configurations
339
+ (e.g., dimensions) used for this class instance.
340
+ """
341
+ try:
342
+ self.binary_index = faiss.read_index_binary(
343
+ index_path
344
+ )
345
+
346
+ except Exception as e:
347
+ print(f"An error occurred while loading the FAISS index: {e}")
348
+
349
+
350
+ def search(
351
+ self,
352
+ query: str,
353
+ top_k: int = 10,
354
+ rescore_multiplier: int = 4
355
+ ) -> Tuple[List[float], List[int]]:
356
+ """
357
+ Performs a search operation against the indexed embeddings.
358
+
359
+ Parameters
360
+ ----------
361
+ query : str
362
+ The query sentence/string to be searched.
363
+
364
+ top_k : int, optional
365
+ The number of top results to return.
366
+
367
+ rescore_multiplier : int, optional
368
+ The multiplier used to increase the initial retrieval size for re-scoring.
369
+ Higher values can increase precision at the cost of performance.
370
+
371
+ Returns
372
+ -------
373
+ Tuple[List[float], List[int]]
374
+ A tuple containing the scores and the indices of the top k results.
375
+
376
+ Notes
377
+ -----
378
+ This method assumes that `binary_index` and `int8_index` are already loaded or created.
379
+ """
380
+ try:
381
+ if self.binary_index is None or self.int8_index is None:
382
+ raise ValueError("Indices must be loaded or created before searching.")
383
+
384
+ query_embedding = self.encode(
385
+ corpus=query,
386
+ normalize_embeddings=False
387
+ )
388
+
389
+ query_embedding_ubinary = self.quantize_embeddings(
390
+ embeddings=query_embedding.reshape(1, -1),
391
+ quantization_type="ubinary"
392
+ )
393
+
394
+ _scores, binary_ids = self.binary_index.search(
395
+ query_embedding_ubinary,
396
+ top_k * rescore_multiplier
397
+ )
398
+
399
+ binary_ids = binary_ids[0]
400
+
401
+ int8_embeddings = self.int8_index[binary_ids].astype(int)
402
+
403
+ scores = query_embedding @ int8_embeddings.T
404
+
405
+ indices = (-scores).argsort()[:top_k]
406
+
407
+ top_k_indices = binary_ids[indices]
408
+ top_k_scores = scores[indices]
409
+
410
+ return top_k_scores.tolist(), top_k_indices.tolist()
411
+
412
+ except Exception as e:
413
+ print(f"An error occurred while searching semantic similar sentences: {e}")
414
+
415
+
416
+ def _quantize_to_ubinary(
417
+ self,
418
+ embeddings: np.ndarray
419
+ ) -> np.ndarray:
420
+ """
421
+ Placeholder private method for ubinary quantization.
422
+
423
+ Parameters
424
+ ----------
425
+ embeddings : np.ndarray
426
+ The embeddings to quantize.
427
+
428
+ Returns
429
+ -------
430
+ np.ndarray
431
+ The quantized embeddings.
432
+ """
433
+ try:
434
+ ubinary_embeddings = quantize_embeddings(
435
+ embeddings,
436
+ "ubinary"
437
+ )
438
+ return ubinary_embeddings
439
+
440
+ except Exception as e:
441
+ print(f"An error occurred during ubinary quantization: {e}")
442
+
443
+
444
+ def _quantize_to_int8(
445
+ self,
446
+ embeddings: np.ndarray
447
+ ) -> np.ndarray:
448
+ """
449
+ Placeholder private method for int8 quantization.
450
+
451
+ Parameters
452
+ ----------
453
+ embeddings : np.ndarray
454
+ The embeddings to quantize.
455
+
456
+ Returns
457
+ -------
458
+ np.ndarray
459
+ The quantized embeddings.
460
+ """
461
+ try:
462
+ int8_embeddings = quantize_embeddings(
463
+ embeddings,
464
+ "int8"
465
+ )
466
+
467
+ return int8_embeddings
468
+
469
+ except Exception as e:
470
+ print(f"An error occurred during int8 quantization: {e}")
471
+
472
+
473
+ def _save_faiss_index_binary(
474
+ self,
475
+ index_path: str
476
+ ) -> None:
477
+ """
478
+ Saves the FAISS binary index to disk.
479
+
480
+ This private method is called internally to save the constructed FAISS binary index to the specified file path.
481
+
482
+ Parameters
483
+ ----------
484
+ index_path : str
485
+ The path to the file where the binary index should be saved. This value is checked in the public method
486
+ `create_faiss_index`.
487
+
488
+ Returns
489
+ -------
490
+ None
491
+
492
+ Notes
493
+ -----
494
+ This method should not be called directly. It is intended to be used internally by the `create_faiss_index` method.
495
+ """
496
+ try:
497
+ faiss.write_index_binary(
498
+ self.binary_index,
499
+ index_path
500
+ )
501
+
502
+ return None
503
+
504
+ except Exception as e:
505
+ print(f"An error occurred during FAISS binary index saving: {e}")
506
+
507
+
508
+ def _save_int8_index(
509
+ self,
510
+ index_path: str
511
+ ) -> None:
512
+ """
513
+ Saves the int8_index to disk.
514
+
515
+ This private method is called internally to save the constructed int8_index to the specified file path.
516
+
517
+ Parameters
518
+ ----------
519
+ index_path : str
520
+ The path to the file where the int8_index should be saved. This value is checked in the public method
521
+ `_save_int8_index`.
522
+
523
+ Returns
524
+ -------
525
+ None
526
+
527
+ Notes
528
+ -----
529
+ This method should not be called directly. It is intended to be used internally by the `_save_int8_index` method.
530
+ """
531
+ try:
532
+ self.int8_index.save(
533
+ index_path
534
+ )
535
+
536
+ return None
537
+
538
+ except Exception as e:
539
+ print(f"An error occurred during int8_index saving: {e}")
usearch_int8.index ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3b756005b791e578b83d0a72d4878ea14cbf8a9cb6b2fd9bb1dede1181d7ae02
3
+ size 145280432