jiang784 commited on
Commit
7db2861
1 Parent(s): 9609d55

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +273 -0
README.md ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ ---
4
+
5
+ For more details please refer to our github repo: https://github.com/FlagOpen/FlagEmbedding
6
+
7
+ # BGE-M3 ([paper](https://arxiv.org/pdf/2402.03216.pdf), [code](https://github.com/FlagOpen/FlagEmbedding/tree/master/FlagEmbedding/BGE_M3))
8
+
9
+ In this project, we introduce BGE-M3, which is distinguished for its versatility in Multi-Functionality, Multi-Linguality, and Multi-Granularity.
10
+ - Multi-Functionality: It can simultaneously perform the three common retrieval functionalities of embedding model: dense retrieval, multi-vector retrieval, and sparse retrieval.
11
+ - Multi-Linguality: It can support more than 100 working languages.
12
+ - Multi-Granularity: It is able to process inputs of different granularities, spanning from short sentences to long documents of up to 8192 tokens.
13
+
14
+ **Some suggestions for retrieval pipeline in RAG:**
15
+ We recommend to use following pipeline: hybrid retrieval + re-ranking.
16
+ - Hybrid retrieval leverages the strengths of various methods, offering higher accuracy and stronger generalization capabilities.
17
+ A classic example: using both embedding retrieval and the BM25 algorithm.
18
+ Now, you can try to use BGE-M3, which supports both embedding and sparse retrieval.
19
+ This allows you to obtain token weights (similar to the BM25) without any additional cost when generate dense embeddings.
20
+ - As cross-encoder models, re-ranker demonstrates higher accuracy than bi-encoder embedding model.
21
+ Utilizing the re-ranking model (e.g., [bge-reranker](https://github.com/FlagOpen/FlagEmbedding/tree/master/FlagEmbedding/reranker), [cohere-reranker](https://txt.cohere.com/rerank/)) after retrieval can further filter the selected text.
22
+
23
+
24
+ ## News:
25
+ - 2/6/2024: We release the [MLDR](https://huggingface.co/datasets/Shitao/MLDR) (a long document retrieval dataset covering 13 languages) and [evaluation pipeline](https://github.com/FlagOpen/FlagEmbedding/tree/master/C_MTEB/MLDR).
26
+ - 2/1/2024: **Thanks for the excellent tool from Vespa.** You can easily use multiple modes of BGE-M3 following this [notebook](https://github.com/vespa-engine/pyvespa/blob/master/docs/sphinx/source/examples/mother-of-all-embedding-models-cloud.ipynb)
27
+
28
+
29
+ ## Specs
30
+
31
+ - Model
32
+
33
+ | Model Name | Dimension | Sequence Length | Introduction |
34
+ |:----:|:---:|:---:|:---:|
35
+ | [BAAI/bge-m3](https://huggingface.co/BAAI/bge-m3) | 1024 | 8192 | multilingual; unified fine-tuning (dense, sparse, and colbert) from bge-m3-unsupervised|
36
+ | [BAAI/bge-m3-unsupervised](https://huggingface.co/BAAI/bge-m3-unsupervised) | 1024 | 8192 | multilingual; contrastive learning from bge-m3-retromae |
37
+ | [BAAI/bge-m3-retromae](https://huggingface.co/BAAI/bge-m3-retromae) | -- | 8192 | multilingual; extend the max_length of [xlm-roberta](https://huggingface.co/FacebookAI/xlm-roberta-large) to 8192 and further pretrained via [retromae](https://github.com/staoxiao/RetroMAE)|
38
+ | [BAAI/bge-large-en-v1.5](https://huggingface.co/BAAI/bge-large-en-v1.5) | 1024 | 512 | English model |
39
+ | [BAAI/bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) | 768 | 512 | English model |
40
+ | [BAAI/bge-small-en-v1.5](https://huggingface.co/BAAI/bge-small-en-v1.5) | 384 | 512 | English model |
41
+
42
+ - Data
43
+
44
+ | Dataset | Introduction |
45
+ |:----:|:---:|
46
+ | [MLDR](https://huggingface.co/datasets/Shitao/MLDR) | Docuemtn Retrieval Dataset, covering 13 languages|
47
+
48
+
49
+ ## FAQ
50
+
51
+ **1. Introduction for different retrieval methods**
52
+
53
+ - Dense retrieval: map the text into a single embedding, e.g., [DPR](https://arxiv.org/abs/2004.04906), [BGE-v1.5](https://github.com/FlagOpen/FlagEmbedding)
54
+ - Sparse retrieval (lexical matching): a vector of size equal to the vocabulary, with the majority of positions set to zero, calculating a weight only for tokens present in the text. e.g., BM25, [unicoil](https://arxiv.org/pdf/2106.14807.pdf), and [splade](https://arxiv.org/abs/2107.05720)
55
+ - Multi-vector retrieval: use multiple vectors to represent a text, e.g., [ColBERT](https://arxiv.org/abs/2004.12832).
56
+
57
+ **2. Comparison with BGE-v1.5 and other monolingual models**
58
+
59
+ BGE-M3 is a multilingual model, and its ability in monolingual embedding retrieval may not surpass models specifically designed for single languages.
60
+ However, we still recommend trying BGE-M3 because of its versatility (support for multiple languages and long texts).
61
+ Moreover, it can simultaneously generate multiple representations, and using them together can enhance accuracy and generalization,
62
+ unlike most existing models that can only perform dense retrieval.
63
+
64
+ In the open-source community, there are many excellent models (e.g., jina-embedding, colbert, e5, etc),
65
+ and users can choose a model that suits their specific needs based on practical considerations,
66
+ such as whether to require multilingual or cross-language support, and whether to process long texts.
67
+
68
+ **3. How to use BGE-M3 in other projects?**
69
+
70
+ For embedding retrieval, you can employ the BGE-M3 model using the same approach as BGE.
71
+ The only difference is that the BGE-M3 model no longer requires adding instructions to the queries.
72
+ For sparse retrieval methods, most open-source libraries currently do not support direct utilization of the BGE-M3 model.
73
+ Contributions from the community are welcome.
74
+
75
+
76
+ In our experiments, we use [Pyserini](https://github.com/FlagOpen/FlagEmbedding/tree/master/C_MTEB/MLDR#hybrid-retrieval-dense--sparse) and Faiss to do hybrid retrieval.
77
+ **Now you can ou can try the hybrid mode of BGE-M3 in [Vespa](https://github.com/vespa-engine/pyvespa/blob/master/docs/sphinx/source/examples/mother-of-all-embedding-models-cloud.ipynb
78
+ ). Thanks @jobergum.**
79
+
80
+
81
+ **4. How to fine-tune bge-M3 model?**
82
+
83
+ You can follow the common in this [example](https://github.com/FlagOpen/FlagEmbedding/tree/master/examples/finetune)
84
+ to fine-tune the dense embedding.
85
+
86
+ Our code and data for unified fine-tuning (dense, sparse, and multi-vectors) will be released.
87
+
88
+
89
+
90
+
91
+ ## Usage
92
+
93
+ Install:
94
+ ```
95
+ git clone https://github.com/FlagOpen/FlagEmbedding.git
96
+ cd FlagEmbedding
97
+ pip install -e .
98
+ ```
99
+ or:
100
+ ```
101
+ pip install -U FlagEmbedding
102
+ ```
103
+
104
+
105
+
106
+ ### Generate Embedding for text
107
+
108
+ - Dense Embedding
109
+ ```python
110
+ from FlagEmbedding import BGEM3FlagModel
111
+
112
+ model = BGEM3FlagModel('BAAI/bge-m3',
113
+ use_fp16=True) # Setting use_fp16 to True speeds up computation with a slight performance degradation
114
+
115
+ sentences_1 = ["What is BGE M3?", "Defination of BM25"]
116
+ sentences_2 = ["BGE M3 is an embedding model supporting dense retrieval, lexical matching and multi-vector interaction.",
117
+ "BM25 is a bag-of-words retrieval function that ranks a set of documents based on the query terms appearing in each document"]
118
+
119
+ embeddings_1 = model.encode(sentences_1,
120
+ batch_size=12,
121
+ max_length=8192, # If you don't need such a long length, you can set a smaller value to speed up the encoding process.
122
+ )['dense_vecs']
123
+ embeddings_2 = model.encode(sentences_2)['dense_vecs']
124
+ similarity = embeddings_1 @ embeddings_2.T
125
+ print(similarity)
126
+ # [[0.6265, 0.3477], [0.3499, 0.678 ]]
127
+ ```
128
+ You also can use sentence-transformers and huggingface transformers to generate dense embeddings.
129
+ Refer to [baai_general_embedding](https://github.com/FlagOpen/FlagEmbedding/tree/master/FlagEmbedding/baai_general_embedding#usage) for details.
130
+
131
+
132
+ - Sparse Embedding (Lexical Weight)
133
+ ```python
134
+ from FlagEmbedding import BGEM3FlagModel
135
+
136
+ model = BGEM3FlagModel('BAAI/bge-m3', use_fp16=True) # Setting use_fp16 to True speeds up computation with a slight performance degradation
137
+
138
+ sentences_1 = ["What is BGE M3?", "Defination of BM25"]
139
+ sentences_2 = ["BGE M3 is an embedding model supporting dense retrieval, lexical matching and multi-vector interaction.",
140
+ "BM25 is a bag-of-words retrieval function that ranks a set of documents based on the query terms appearing in each document"]
141
+
142
+ output_1 = model.encode(sentences_1, return_dense=True, return_sparse=True, return_colbert_vecs=False)
143
+ output_2 = model.encode(sentences_2, return_dense=True, return_sparse=True, return_colbert_vecs=False)
144
+
145
+ # you can see the weight for each token:
146
+ print(model.convert_id_to_token(output_1['lexical_weights']))
147
+ # [{'What': 0.08356, 'is': 0.0814, 'B': 0.1296, 'GE': 0.252, 'M': 0.1702, '3': 0.2695, '?': 0.04092},
148
+ # {'De': 0.05005, 'fin': 0.1368, 'ation': 0.04498, 'of': 0.0633, 'BM': 0.2515, '25': 0.3335}]
149
+
150
+
151
+ # compute the scores via lexical mathcing
152
+ lexical_scores = model.compute_lexical_matching_score(output_1['lexical_weights'][0], output_2['lexical_weights'][0])
153
+ print(lexical_scores)
154
+ # 0.19554901123046875
155
+
156
+ print(model.compute_lexical_matching_score(output_1['lexical_weights'][0], output_1['lexical_weights'][1]))
157
+ # 0.0
158
+ ```
159
+
160
+ - Multi-Vector (ColBERT)
161
+ ```python
162
+ from FlagEmbedding import BGEM3FlagModel
163
+
164
+ model = BGEM3FlagModel('BAAI/bge-m3', use_fp16=True)
165
+
166
+ sentences_1 = ["What is BGE M3?", "Defination of BM25"]
167
+ sentences_2 = ["BGE M3 is an embedding model supporting dense retrieval, lexical matching and multi-vector interaction.",
168
+ "BM25 is a bag-of-words retrieval function that ranks a set of documents based on the query terms appearing in each document"]
169
+
170
+ output_1 = model.encode(sentences_1, return_dense=True, return_sparse=True, return_colbert_vecs=True)
171
+ output_2 = model.encode(sentences_2, return_dense=True, return_sparse=True, return_colbert_vecs=True)
172
+
173
+ print(model.colbert_score(output_1['colbert_vecs'][0], output_2['colbert_vecs'][0]))
174
+ print(model.colbert_score(output_1['colbert_vecs'][0], output_2['colbert_vecs'][1]))
175
+ # 0.7797
176
+ # 0.4620
177
+ ```
178
+
179
+
180
+ ### Compute score for text pairs
181
+ Input a list of text pairs, you can get the scores computed by different methods.
182
+ ```python
183
+ from FlagEmbedding import BGEM3FlagModel
184
+
185
+ model = BGEM3FlagModel('BAAI/bge-m3', use_fp16=True)
186
+
187
+ sentences_1 = ["What is BGE M3?", "Defination of BM25"]
188
+ sentences_2 = ["BGE M3 is an embedding model supporting dense retrieval, lexical matching and multi-vector interaction.",
189
+ "BM25 is a bag-of-words retrieval function that ranks a set of documents based on the query terms appearing in each document"]
190
+
191
+ sentence_pairs = [[i,j] for i in sentences_1 for j in sentences_2]
192
+
193
+ print(model.compute_score(sentence_pairs,
194
+ max_passage_length=128, # a smaller max length leads to a lower latency
195
+ weights_for_different_modes=[0.4, 0.2, 0.4])) # weights_for_different_modes(w) is used to do weighted sum: w[0]*dense_score + w[1]*sparse_score + w[2]*colbert_score
196
+
197
+ # {
198
+ # 'colbert': [0.7796499729156494, 0.4621465802192688, 0.4523794651031494, 0.7898575067520142],
199
+ # 'sparse': [0.195556640625, 0.00879669189453125, 0.0, 0.1802978515625],
200
+ # 'dense': [0.6259765625, 0.347412109375, 0.349853515625, 0.67822265625],
201
+ # 'sparse+dense': [0.482503205537796, 0.23454029858112335, 0.2332356721162796, 0.5122477412223816],
202
+ # 'colbert+sparse+dense': [0.6013619303703308, 0.3255828022956848, 0.32089319825172424, 0.6232916116714478]
203
+ # }
204
+ ```
205
+
206
+
207
+
208
+
209
+ ## Evaluation
210
+
211
+
212
+ **Currently, the results of BM25 on non-English data are incorrect.
213
+ We will review our testing process and update the paper as soon as possible.
214
+ For more powerful BM25, you can refer to this [repo](https://github.com/carlos-lassance/bm25_mldr).
215
+ Thanks to the community for the reminder and to carlos-lassance for providing the results.**
216
+
217
+
218
+ - Multilingual (Miracl dataset)
219
+
220
+ ![avatar](./imgs/miracl.jpg)
221
+
222
+ - Cross-lingual (MKQA dataset)
223
+
224
+ ![avatar](./imgs/mkqa.jpg)
225
+
226
+ - Long Document Retrieval
227
+ - MLDR:
228
+ ![avatar](./imgs/long.jpg)
229
+ Please note that [MLDR](https://huggingface.co/datasets/Shitao/MLDR) is a document retrieval dataset we constructed via LLM,
230
+ covering 13 languages, including test set, validation set, and training set.
231
+ We utilized the training set from MLDR to enhance the model's long document retrieval capabilities.
232
+ Therefore, comparing baselines with `Dense w.o.long`(fine-tuning without long document dataset) is more equitable.
233
+ Additionally, this long document retrieval dataset will be open-sourced to address the current lack of open-source multilingual long text retrieval datasets.
234
+ We believe that this data will be helpful for the open-source community in training document retrieval models.
235
+
236
+ - NarritiveQA:
237
+ ![avatar](./imgs/nqa.jpg)
238
+
239
+
240
+ ## Training
241
+ - Self-knowledge Distillation: combining multiple outputs from different
242
+ retrieval modes as reward signal to enhance the performance of single mode(especially for sparse retrieval and multi-vec(colbert) retrival)
243
+ - Efficient Batching: Improve the efficiency when fine-tuning on long text.
244
+ The small-batch strategy is simple but effective, which also can used to fine-tune large embedding model.
245
+ - MCLS: A simple method to improve the performance on long text without fine-tuning.
246
+ If you have no enough resource to fine-tuning model with long text, the method is useful.
247
+
248
+ Refer to our [report](https://arxiv.org/pdf/2402.03216.pdf) for more details.
249
+
250
+ **The fine-tuning codes and datasets will be open-sourced in the near future.**
251
+
252
+
253
+ ## Acknowledgement
254
+
255
+ Thanks the authors of open-sourced datasets, including Miracl, MKQA, NarritiveQA, etc.
256
+ Thanks the open-sourced libraries like [Tevatron](https://github.com/texttron/tevatron), [pyserial](https://github.com/pyserial/pyserial).
257
+
258
+
259
+
260
+ ## Citation
261
+
262
+ If you find this repository useful, please consider giving a star :star: and citation
263
+
264
+ ```
265
+ @misc{bge-m3,
266
+ title={BGE M3-Embedding: Multi-Lingual, Multi-Functionality, Multi-Granularity Text Embeddings Through Self-Knowledge Distillation},
267
+ author={Jianlv Chen and Shitao Xiao and Peitian Zhang and Kun Luo and Defu Lian and Zheng Liu},
268
+ year={2024},
269
+ eprint={2402.03216},
270
+ archivePrefix={arXiv},
271
+ primaryClass={cs.CL}
272
+ }
273
+ ```