Sentence Similarity
sentence-transformers
PyTorch
Safetensors
xmod
passage-retrieval
antoinelouis commited on
Commit
9442503
·
verified ·
1 Parent(s): 46685c5

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +202 -76
README.md CHANGED
@@ -1,129 +1,255 @@
1
  ---
2
  pipeline_tag: sentence-similarity
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  tags:
4
- - sentence-transformers
5
  - feature-extraction
6
  - sentence-similarity
7
- - transformers
8
-
9
  ---
10
 
11
- # {MODEL_NAME}
12
 
13
- This is a [sentence-transformers](https://www.SBERT.net) model: It maps sentences & paragraphs to a 768 dimensional dense vector space and can be used for tasks like clustering or semantic search.
14
 
15
- <!--- Describe your model here -->
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
- ## Usage (Sentence-Transformers)
18
 
19
- Using this model becomes easy when you have [sentence-transformers](https://www.SBERT.net) installed:
20
 
21
- ```
22
- pip install -U sentence-transformers
23
- ```
24
 
25
- Then you can use the model like this:
 
 
26
 
27
  ```python
28
  from sentence_transformers import SentenceTransformer
29
- sentences = ["This is an example sentence", "Each sentence is converted"]
30
 
31
- model = SentenceTransformer('{MODEL_NAME}')
32
- embeddings = model.encode(sentences)
33
- print(embeddings)
34
- ```
 
 
35
 
 
 
36
 
 
 
 
 
 
37
 
38
- ## Usage (HuggingFace Transformers)
39
- Without [sentence-transformers](https://www.SBERT.net), you can use the model like this: First, you pass your input through the transformer model, then you have to apply the right pooling-operation on-top of the contextualized word embeddings.
40
 
41
  ```python
42
  from transformers import AutoTokenizer, AutoModel
43
- import torch
44
 
45
-
46
- #Mean Pooling - Take attention mask into account for correct averaging
47
  def mean_pooling(model_output, attention_mask):
 
48
  token_embeddings = model_output[0] #First element of model_output contains all token embeddings
49
  input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
50
  return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
51
 
52
 
53
- # Sentences we want sentence embeddings for
54
- sentences = ['This is an example sentence', 'Each sentence is converted']
55
-
56
- # Load model from HuggingFace Hub
57
- tokenizer = AutoTokenizer.from_pretrained('{MODEL_NAME}')
58
- model = AutoModel.from_pretrained('{MODEL_NAME}')
59
 
60
- # Tokenize sentences
61
- encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
 
62
 
63
- # Compute token embeddings
 
64
  with torch.no_grad():
65
- model_output = model(**encoded_input)
 
 
 
 
 
 
 
 
 
66
 
67
- # Perform pooling. In this case, mean pooling.
68
- sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
69
 
70
- print("Sentence embeddings:")
71
- print(sentence_embeddings)
72
- ```
 
 
 
 
 
73
 
 
 
74
 
 
 
 
 
 
 
75
 
76
- ## Evaluation Results
77
 
78
- <!--- Describe how your model was evaluated -->
79
 
80
- For an automated evaluation of this model, see the *Sentence Embeddings Benchmark*: [https://seb.sbert.net](https://seb.sbert.net?model_name={MODEL_NAME})
 
81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
  ## Training
84
- The model was trained with the parameters:
85
 
86
- **DataLoader**:
87
 
88
- `torch.utils.data.dataloader.DataLoader` of length 1950 with parameters:
89
- ```
90
- {'batch_size': 256, 'sampler': 'torch.utils.data.sampler.RandomSampler', 'batch_sampler': 'torch.utils.data.sampler.BatchSampler'}
91
- ```
92
 
93
- **Loss**:
94
 
95
- `sentence_transformers.losses.MultipleNegativesRankingLoss.MultipleNegativesRankingLoss` with parameters:
96
- ```
97
- {'scale': 20.0, 'similarity_fct': 'cos_sim'}
98
- ```
99
 
100
- Parameters of the fit()-Method:
101
- ```
102
- {
103
- "epochs": 40,
104
- "evaluation_steps": 0,
105
- "evaluator": "NoneType",
106
- "max_grad_norm": 1,
107
- "optimizer_class": "<class 'torch.optim.adamw.AdamW'>",
108
- "optimizer_params": {
109
- "lr": 2e-05
110
- },
111
- "scheduler": "warmuplinear",
112
- "steps_per_epoch": null,
113
- "warmup_steps": 7800,
114
- "weight_decay": 0.01
115
- }
116
- ```
117
 
 
118
 
119
- ## Full Model Architecture
120
- ```
121
- SentenceTransformerCustom(
122
- (0): Transformer({'max_seq_length': 128, 'do_lower_case': False}) with Transformer model: XmodModel
123
- (1): Pooling({'word_embedding_dimension': 768, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': True, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False, 'pooling_mode_weightedmean_tokens': False, 'pooling_mode_lasttoken': False})
124
- )
 
 
 
 
 
 
 
 
 
 
125
  ```
126
 
127
- ## Citing & Authors
128
 
129
- <!--- Describe where people can find more information -->
 
1
  ---
2
  pipeline_tag: sentence-similarity
3
+ language:
4
+ - multilingual
5
+ - af
6
+ - am
7
+ - ar
8
+ - az
9
+ - be
10
+ - bg
11
+ - bn
12
+ - ca
13
+ - cs
14
+ - cy
15
+ - da
16
+ - de
17
+ - el
18
+ - en
19
+ - eo
20
+ - es
21
+ - et
22
+ - eu
23
+ - fa
24
+ - fi
25
+ - fr
26
+ - ga
27
+ - gl
28
+ - gu
29
+ - ha
30
+ - he
31
+ - hi
32
+ - hr
33
+ - hu
34
+ - hy
35
+ - id
36
+ - is
37
+ - it
38
+ - ja
39
+ - ka
40
+ - kk
41
+ - km
42
+ - kn
43
+ - ko
44
+ - ku
45
+ - ky
46
+ - la
47
+ - lo
48
+ - lt
49
+ - lv
50
+ - mk
51
+ - ml
52
+ - mn
53
+ - mr
54
+ - ms
55
+ - my
56
+ - ne
57
+ - nl
58
+ - no
59
+ - or
60
+ - pa
61
+ - pl
62
+ - ps
63
+ - pt
64
+ - ro
65
+ - ru
66
+ - sa
67
+ - si
68
+ - sk
69
+ - sl
70
+ - so
71
+ - sq
72
+ - sr
73
+ - sv
74
+ - sw
75
+ - ta
76
+ - te
77
+ - th
78
+ - tl
79
+ - tr
80
+ - uk
81
+ - ur
82
+ - uz
83
+ - vi
84
+ - zh
85
+ license: apache-2.0
86
+ datasets:
87
+ - ms_marco
88
+ - sentence-transformers/msmarco-hard-negatives
89
+ metrics:
90
+ - recall
91
  tags:
 
92
  - feature-extraction
93
  - sentence-similarity
94
+ library_name: sentence-transformers
 
95
  ---
96
 
97
+ <h1 align="center">DPR-XM</h1>
98
 
 
99
 
100
+ <h4 align="center">
101
+ <p>
102
+ <a href=#usage>🛠️ Usage</a> |
103
+ <a href="#evaluation">📊 Evaluation</a> |
104
+ <a href="#train">🤖 Training</a> |
105
+ <a href="#citation">🔗 Citation</a> |
106
+ <a href="#license">🔑 License</a>
107
+ <p>
108
+ <p>
109
+ <a href="https://github.com/ant-louis/xm-retrievers">💻 Code</a> |
110
+ <a href="https://arxiv.org/abs/">📄 Paper</a>
111
+ <p>
112
+ </h4>
113
 
 
114
 
115
+ This is a [sentence-transformers](https://www.SBERT.net) model. It maps questions and paragraphs 768-dimensional dense vectors and can be used for semantic search. The model uses an [XMOD](https://huggingface.co/facebook/xmod-base) backbone, which allows it to learn from monolingual fine-tuning in a high-resource language, like English, and perform zero-shot retrieval across multiple languages.
116
 
117
+ ## Usage
118
+
119
+ Here are some examples for using DPR-XM with [Sentence-Transformers](#using-sentence-transformers), [FlagEmbedding](#using-flagembedding), and [Huggingface Transformers](#using-huggingface-transformers).
120
 
121
+ #### Using Sentence-Transformers
122
+
123
+ Start by installing the [library](https://www.SBERT.net): `pip install -U sentence-transformers`. Then, you can use the model like this:
124
 
125
  ```python
126
  from sentence_transformers import SentenceTransformer
 
127
 
128
+ queries = ["Ceci est un exemple de requête.", "Voici un second exemple."]
129
+ passages = ["Ceci est un exemple de passage.", "Et voilà un deuxième exemple."]
130
+ language_code = "fr_FR" #Find all codes here: https://huggingface.co/facebook/xmod-base#languages
131
+
132
+ model = SentenceTransformer('antoinelouis/dpr-xm')
133
+ model[0].auto_model.set_default_language(language_code) #Activate the language-specific adapters
134
 
135
+ q_embeddings = model.encode(queries, normalize_embeddings=True)
136
+ p_embeddings = model.encode(passages, normalize_embeddings=True)
137
 
138
+ similarity = q_embeddings @ p_embeddings.T
139
+ print(similarity)
140
+ ```
141
+
142
+ #### Using Transformers
143
 
144
+ Start by installing the [library](https://huggingface.co/docs/transformers): `pip install -U transformers`. Then, you can use the model like this:
 
145
 
146
  ```python
147
  from transformers import AutoTokenizer, AutoModel
148
+ from torch.nn.functional import normalize
149
 
 
 
150
  def mean_pooling(model_output, attention_mask):
151
+ """ Perform mean pooling on-top of the contextualized word embeddings, while ignoring mask tokens in the mean computation."""
152
  token_embeddings = model_output[0] #First element of model_output contains all token embeddings
153
  input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
154
  return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
155
 
156
 
157
+ queries = ["Ceci est un exemple de requête.", "Voici un second exemple."]
158
+ passages = ["Ceci est un exemple de passage.", "Et voilà un deuxième exemple."]
159
+ language_code = "fr_FR" #Find all codes here: https://huggingface.co/facebook/xmod-base#languages
 
 
 
160
 
161
+ tokenizer = AutoTokenizer.from_pretrained('antoinelouis/dpr-xm')
162
+ model = AutoModel.from_pretrained('antoinelouis/dpr-xm')
163
+ model.set_default_language(language_code) #Activate the language-specific adapters
164
 
165
+ q_input = tokenizer(queries, padding=True, truncation=True, return_tensors='pt')
166
+ p_input = tokenizer(passages, padding=True, truncation=True, return_tensors='pt')
167
  with torch.no_grad():
168
+ q_output = model(**encoded_queries)
169
+ p_output = model(**encoded_passages)
170
+ q_embeddings = mean_pooling(q_output, q_input['attention_mask'])
171
+ q_embedddings = normalize(q_embeddings, p=2, dim=1)
172
+ p_embeddings = mean_pooling(p_output, p_input['attention_mask'])
173
+ p_embedddings = normalize(p_embeddings, p=2, dim=1)
174
+
175
+ similarity = q_embeddings @ p_embeddings.T
176
+ print(similarity)
177
+ ```
178
 
179
+ #### Using FlagEmbedding
 
180
 
181
+ Start by installing the [library](https://github.com/FlagOpen/FlagEmbedding/): `pip install -U FlagEmbedding`. Then, you can use the model like this:
182
+
183
+ ```python
184
+ from FlagEmbedding import FlagModel
185
+
186
+ queries = ["Ceci est un exemple de requête.", "Voici un second exemple."]
187
+ passages = ["Ceci est un exemple de passage.", "Et voilà un deuxième exemple."]
188
+ language_code = "fr_FR" #Find all codes here: https://huggingface.co/facebook/xmod-base#languages
189
 
190
+ model = FlagModel('antoinelouis/dpr-xm')
191
+ model.model.set_default_language(language_code) #Activate the language-specific adapters
192
 
193
+ q_embeddings = model.encode(queries, normalize_embeddings=True)
194
+ p_embeddings = model.encode(passages, normalize_embeddings=True)
195
+
196
+ similarity = q_embeddings @ p_embeddings.T
197
+ print(similarity)
198
+ ```
199
 
200
+ ***
201
 
202
+ ## Evaluation
203
 
204
+ - **MS MARCO**:
205
+ We evaluate our model on the small development set of [MS MARCO](https://ir-datasets.com/msmarco-passage.html#msmarco-passage/dev/small), which consists of 6,980 queries for a corpus of 8.8M candidate passages. Below, we compared its performance with other retrieval models on the official metrics for the dataset, i.e., mean reciprocal rank at cut-off 10 (MRR@10).
206
 
207
+ | | model | Type | #Samples | #Params | en | es | fr | it | pt | id | de | ru | zh | ja | nl | vi | hi | ar | Avg. |
208
+ |---:|:--------------------------------------------------------------------------------------------------------------------------------|:--------------|:---------|--------:|-----:|-----:|-----:|-----:|-----:|-----:|-----:|-----:|-----:|-----:|-----:|-----:|-----:|-----:|-----:|
209
+ | 1 | BM25 ([Pyserini](https://github.com/castorini/pyserini)) | lexical | - | - | 18.4 | 15.8 | 15.5 | 15.3 | 15.2 | 14.9 | 13.6 | 12.4 | 11.6 | 14.1 | 14.0 | 13.6 | 13.4 | 11.1 | 14.2 |
210
+ | 2 | mono-mT5 ([Bonfacio et al., 2021](https://arxiv.org/abs/2108.13897)) | cross-encoder | 12.8M | 390M | 36.6 | 31.4 | 30.2 | 30.3 | 30.2 | 29.8 | 28.9 | 26.3 | 24.9 | 26.7 | 29.2 | 25.6 | 26.6 | 23.5 | 28.6 |
211
+ | 3 | mono-mMiniLM ([Bonfacio et al., 2021](https://arxiv.org/abs/2108.13897)) | cross-encoder | 80.0M | 107M | 36.6 | 30.9 | 29.6 | 29.1 | 28.9 | 29.3 | 27.8 | 25.1 | 24.9 | 26.3 | 27.6 | 24.7 | 26.2 | 21.9 | 27.8 |
212
+ | 4 | [DPR-X](https://huggingface.co/eugene-yang/dpr-xlmr-large-mtt-neuclir) ([Yang et al., 2022](https://arxiv.org/abs/2204.11989)) | single-vector | 25.6M | 550M | 24.5 | 19.6 | 18.9 | 18.3 | 19.0 | 16.9 | 18.2 | 17.7 | 14.8 | 15.4 | 18.5 | 15.1 | 15.4 | 12.9 | 17.5 |
213
+ | 5 | [mE5-base](https://huggingface.co/intfloat/multilingual-e5-base) ([Wang et al., 2024](https://arxiv.org/abs/2402.05672)) | single-vector | 5.1B | 278M | 35.0 | 28.9 | 30.3 | 28.0 | 27.5 | 26.1 | 27.1 | 24.5 | 22.9 | 25.0 | 27.3 | 23.9 | 24.2 | 20.5 | 26.5 |
214
+ | 6 | mColBERT ([Bonfacio et al., 2021](https://arxiv.org/abs/2108.13897)) | multi-vector | 25.6M | 180M | 35.2 | 30.1 | 28.9 | 29.2 | 29.2 | 27.5 | 28.1 | 25.0 | 24.6 | 23.6 | 27.3 | 18.0 | 23.2 | 20.9 | 26.5 |
215
+ | | | | | | | | | | | | | | | | | | | | |
216
+ | 7 | **DPR-XM** (ours) | single-vector | 25.6M | 277M | 32.7 | 23.6 | 23.5 | 22.3 | 22.7 | 22.0 | 22.1 | 19.9 | 18.1 | 18.7 | 22.9 | 18.0 | 16.0 | 15.1 | 21.3 |
217
+ | 8 | [ColBERT-XM](https://huggingface.co/antoinelouis/colbert-xm) (ours) | multi-vector | 6.4M | 277M | 37.2 | 28.5 | 26.9 | 26.5 | 27.6 | 26.3 | 27.0 | 25.1 | 24.6 | 24.1 | 27.5 | 22.6 | 23.8 | 19.5 | 26.2 |
218
+
219
+ ***
220
 
221
  ## Training
 
222
 
223
+ #### Background
224
 
225
+ We use the [xmod-base](https://huggingface.co/facebook/xmod-base) backbone and fine-tune it on 25.6M MS MARCO triples. We optimize the model with a contrastive learning objective: given a sentence from the pair, the model should predict which out of a set of randomly sampled other sentences, was actually paired with it in the dataset. Formally, we compute the cos similarity from each possible sentence pairs from the batch. We then apply the cross entropy loss with a temperature of 0.05 by comparing with true pairs.
 
 
 
226
 
227
+ #### Hyperparameters
228
 
229
+ We traine the model on a single Tesla V100 GPU with 32GBs of memory for 200k steps using a batch size of 128. We use the AdamW optimizer with a peak learning rate of 2e-5 with warm up along the first 10\% of training steps and linear scheduling. The sequence length was limited to 128 tokens.
 
 
 
230
 
231
+ #### Data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
 
233
+ We use training triples from the [MS MARCO passage ranking](https://ir-datasets.com/msmarco-passage.html#msmarco-passage/train) dataset, which contains 8.8M passages and 539K training queries. We sample hard negatives mined from 12 distinct dense retrievers using the [msmarco-hard-negatives](https://huggingface.co/datasets/sentence-transformers/msmarco-hard-negatives) distillation dataset.
234
 
235
+ ***
236
+
237
+ ## Citation
238
+
239
+ ```bibtex
240
+ @article{louis2024modular,
241
+ author = {Louis, Antoine and Saxena, Vageesh and van Dijck, Gijs and Spanakis, Gerasimos},
242
+ title = {ColBERT-XM: A Modular Multi-Vector Representation Model for Zero-Shot Multilingual Information Retrieval},
243
+ journal = {CoRR},
244
+ volume = {abs/2402.xxxxx},
245
+ year = {2024},
246
+ url = {https://doi.org/},
247
+ doi = {},
248
+ eprinttype = {arXiv},
249
+ eprint = {2402.xxxxx},
250
+ }
251
  ```
252
 
253
+ ## License
254
 
255
+ DPR-XM is licensed under the [Apache 2.0](https://opensource.org/license/apache-2-0/) license.